Speeding up a script that checks ACLs on every folder

I have a script that is looking for a very specific level of NTFS access permissions, specifically a specific SDDL. I already know that SDDL and have checked to make sure that I can submit the SDDL as a test string and compare it against a get-acl SDDL.
The problem is this takes a long time (about 4 minutes for 4300 folders) and I've been asked to search through a few hundred thousand folders. Here's the code I have so far:
$folders = gci c:\foo -Directory -Recurse
ForEach ($folder in $folders)
$path = $folder.fullname
$acl = get-acl $path
if ($acl.sddl -eq "O:BAG:DUD:PARAI(A;OICI;FA;;;BA)") {write-host -ForegroundColor Red "$path has only admins"}}
Obviously I'll want to output to something other than my screen, but essentially I'm looking for ideas to speed that up.
[email protected]

Go here and get the LongPath.zip file. Inside it should be a file named 'Microsoft.Experimental.IO.dll'. You can use that with the code below to get around the 248 character path limit, and it should
be pretty fast, too. Just fill in the first few variables with the information you're looking for. Note that it is possible for a security descriptor's effective access to be identical to another one that has a different SDDL string (I don't think that will
happen here, though, because of the use of the CommonSecurityDescriptor class).
This creates a C# class that uses the LongPath methods to list files and folders, and it uses the GetNamedSecurityInfo() API call along with the paths to get the binary form of the security descriptors. The searching for the SDDL happens inside of a C# method,
too, to try to speed things up. I'm not really a C# developer, so someone else could probably make this even faster. Please give it a shot, though, and let me know if it works for you:
$ExperimentalIoPath = "C:\path\to\Microsoft.Experimental.IO.dll"
$PathToSearch = "c:\path\to\search"
$SddlToFind = "O:BAG:DUD:PARAI(A;OICI;FA;;;BA)"
Add-Type -Path $ExperimentalIoPath
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Collections.Generic;
using Microsoft.Experimental.IO;
namespace HSG {
public class Helper {
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa446645%28v=vs.85%29.aspx
[DllImport("advapi32.dll", EntryPoint = "GetNamedSecurityInfoW", CharSet = CharSet.Unicode)]
internal static extern uint GetNamedSecurityInfo(
string ObjectName,
System.Security.AccessControl.ResourceType ObjectType,
SecurityInformation SecurityInfo,
out IntPtr pSidOwner,
out IntPtr pSidGroup,
out IntPtr pDacl,
out IntPtr pSacl,
out IntPtr pSecurityDescriptor
[DllImport("advapi32.dll")]
internal static extern Int32 GetSecurityDescriptorLength(
IntPtr pSecurityDescriptor
[DllImport("kernel32.dll", SetLastError=true)]
internal static extern IntPtr LocalFree(
IntPtr hMem
[Flags]
public enum SecurityInformation : uint {
Owner = 0x00000001,
Group = 0x00000002,
Dacl = 0x00000004,
Sacl = 0x00000008
public static CommonSecurityDescriptor GetSecurityDescriptor(string path, System.Security.AccessControl.ResourceType objectType, SecurityInformation securityInformation, bool isContainer) {
IntPtr pOwner, pGroup, pDacl, pSacl, pSecurityDescriptor;
pOwner = pGroup = pDacl = pSacl = pSecurityDescriptor = IntPtr.Zero;
uint exitCode;
exitCode = GetNamedSecurityInfo(path, objectType, securityInformation, out pOwner, out pGroup, out pDacl, out pSacl, out pSecurityDescriptor);
if (exitCode != 0) {
throw new Exception((new System.ComponentModel.Win32Exception(Convert.ToInt32(exitCode))).Message);
if (pSecurityDescriptor == IntPtr.Zero) {
throw new Exception(String.Format("No security descriptor available for {0} object with path {1}", objectType, path));
byte[] binarySd;
try {
int sdSize = GetSecurityDescriptorLength(pSecurityDescriptor);
binarySd = new byte[sdSize];
Marshal.Copy(pSecurityDescriptor, binarySd, 0, sdSize);
catch(Exception e) {
throw e;
finally {
if (LocalFree(pSecurityDescriptor) != IntPtr.Zero) {
throw new Exception(String.Format("Error freeing memory for security descriptor at path {0}", path));
return new CommonSecurityDescriptor(isContainer, false, binarySd, 0);
public class LongPathFileSystemItem {
public LongPathFileSystemItem(string path, bool isContainer) {
this.Path = path;
this.IsContainer = isContainer;
public string Path { get; private set; }
public bool IsContainer { get; private set; }
public static List<LongPathFileSystemItem> GetChildItemLongPath(string path, bool recurse) {
List<LongPathFileSystemItem> results = new List<LongPathFileSystemItem>();
try {
// Get directories
foreach (string folderName in LongPathDirectory.EnumerateDirectories(path)) {
if (recurse) {
results.AddRange(GetChildItemLongPath(folderName, true));
results.Add(new LongPathFileSystemItem(folderName, true));
// Get files:
foreach (string fileName in LongPathDirectory.EnumerateFiles(path)) {
results.Add(new LongPathFileSystemItem(fileName, false));
catch (Exception e) {
// Not the best way to handle errors, but didn't want to terminate
results.Add(new LongPathFileSystemItem(string.Format("Error enumerating FS objects for '{0}': {1}", path, e.Message), false));
return results;
public static List<string> GetFileSystemObjectsWithSpecificSddl(string path, string sddl, bool recurse) {
List<string> results = new List<string>();
string currentSddl;
foreach (LongPathFileSystemItem childItem in GetChildItemLongPath(path, recurse)) {
if (childItem.Path.StartsWith("Error")) {
results.Add(childItem.Path);
continue;
try {
currentSddl = GetSecurityDescriptor(
string.Format(@"\\?\{0}", childItem.Path),
ResourceType.FileObject,
SecurityInformation.Owner | SecurityInformation.Group | SecurityInformation.Dacl,
childItem.IsContainer
).GetSddlForm(AccessControlSections.All);
catch (Exception e) {
results.Add(string.Format("Error getting security descriptor for '{0}': {1}", childItem.Path, e.Message));
continue;
if (sddl == currentSddl) {
results.Add(childItem.Path);
return results;
"@ -ReferencedAssemblies $ExperimentalIoPath
function Search-Sddl {
[OutputType([string])]
[CmdletBinding()]
param(
[string] $Path,
[string] $Sddl,
[switch] $Recurse
process {
[HSG.Helper]::GetFileSystemObjectsWithSpecificSddl($Path, $SddlToFind, $Recurse) | ForEach-Object {
if ($_ -match "^Error") { Write-Error $_ }
else { $_ }
#All of that is used to define the Search-Sddl function, which is used like this:
Search-Sddl -Path $PathToSearch -Sddl $SddlToFind -Recurse

Similar Messages

  • Bash script for checking link status

    So I'm doing some SEO work I've been tasked with checking a couple hundred thousand back links for quality.  I found myself spending a lot of time navigating to sites that no longer existed.  I figured I would make a bash script that checks if the links are active first.  The problem is my script is slower than evolution.  I'm no bash guru or anything so I figured maybe I would see if there are some optimizations you folks can think of.  Here is what I am working with:
    #!/bin/bash
    while read line
    do
    #pull page source and grep for domain
    curl -s "$line" | grep "example.com"
    if [[ $? -eq 0 ]]
    then
    echo \"$line\",\"link active\" >> csv.csv else
    echo \"$line\",\"REMOVED\" >> csv.csv
    fi
    done < <(cat links.txt)
    Can you guys think of another way of doing this that might be quicker?  I realize the bottleneck is curl (as well as the speed of the remote server/dns servers) and that there isn't really a way around that.  Is there another tool or technique I could use within my script to speed up this process?
    I will still have to go through the active links one by one and analyze by hand but I don't think there is a good way of doing this programmatically that wouldn't consume more time than doing it by hand (if it's even possible).
    Thanks

    I know it's been awhile but I've found myself in need of this yet again.  I've modified Xyne's script a little to work a little more consistently with my data.  The problem I'm running into now is that urllib doesn't accept IRIs.  No surprise there I suppose as it's urllib and not irilib.  Does anyone know of any libraries that will convert an IRI to a URI?  Here is the code I am working with:
    #!/usr/bin/env python3
    from threading import Thread
    from queue import Queue
    from urllib.request import Request, urlopen
    from urllib.error import URLError
    import csv
    import sys
    import argparse
    parser = argparse.ArgumentParser(description='Check list of URLs for existence of link in html')
    parser.add_argument('-d','--domain', help='The domain you would like to search for a link to', required=True)
    parser.add_argument('-i','--input', help='Text file with list of URLs to check', required=True)
    parser.add_argument('-o','--output', help='Named of csv to output results to', required=True)
    parser.add_argument('-v','--verbose', help='Display URLs and statuses in the terminal', required=False, action='store_true')
    ARGS = vars(parser.parse_args())
    INFILE = ARGS['input']
    OUTFILE = ARGS['output']
    DOMAIN = ARGS['domain']
    REMOVED = 'REMOVED'
    EXISTS = 'EXISTS'
    NUMBER_OF_WORKERS = 50
    #Workers
    def worker(input_queue, output_queue):
    while True:
    url = input_queue.get()
    if url is None:
    input_queue.task_done()
    input_queue.put(None)
    break
    request = Request(url)
    try:
    response = urlopen(request)
    html = str(response.read())
    if DOMAIN in html:
    status = EXISTS
    else:
    status = REMOVED
    except URLError:
    status = REMOVED
    output_queue.put((url, status))
    input_queue.task_done()
    #Queues
    input_queue = Queue()
    output_queue = Queue()
    #Create threads
    for i in range(NUMBER_OF_WORKERS):
    t = Thread(target=worker, args=(input_queue, output_queue))
    t.daemon = True
    t.start()
    #Populate input queue
    number_of_urls = 0
    with open(INFILE, 'r') as f:
    for line in f:
    input_queue.put(line.strip())
    number_of_urls += 1
    input_queue.put(None)
    #Write URL and Status to csv file
    with open(OUTFILE, 'a') as f:
    c = csv.writer(f, delimiter=',', quotechar='"')
    for i in range(number_of_urls):
    url, status = output_queue.get()
    if ARGS['verbose']:
    print('{}\n {}'.format(url, status))
    c.writerow((url, status))
    output_queue.task_done()
    input_queue.get()
    input_queue.task_done()
    input_queue.join()
    output_queue.join()
    The problem seems to be when I use urlopen
    response = urlopen(request)
    with a URL like http://www.rafo.co.il/בר-פאלי-p1
    urlopen fails with an error like this:
    Exception in thread Thread-19:
    Traceback (most recent call last):
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 639, in _bootstrap_inner
    self.run()
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 596, in run
    self._target(*self._args, **self._kwargs)
    File "./linkcheck.py", line 35, in worker
    response = urlopen(request)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 160, in urlopen
    return opener.open(url, data, timeout)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 473, in open
    response = self._open(req, data)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 491, in _open
    '_open', req)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1272, in http_open
    return self.do_open(http.client.HTTPConnection, req)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1252, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1049, in request
    self._send_request(method, url, body, headers)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1077, in _send_request
    self.putrequest(method, url, **skips)
    File "/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 941, in putrequest
    self._output(request.encode('ascii'))
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-8: ordinal not in range(128)
    I'm not too familiar with how character encoding works so I'm not sure where to start.  What would be a quick and dirty way (if one exists) to get URLs like this to play nicely with python's urlopen?

  • Can IFS be set up so that new files inherit the ACL of the folder they are created in

    I realise that a file created or saved in IFS takes on the ACL of the User who created it. This is fine if users always save items into the same folders or belong to a single group. However, it causes problems when users need to save different items in many folders, each of which may have different audiences/require different security.
    With this in mind, is it possible to set up IFS so that a file inherits the ACL of the folder in which it was created/saved, at creation/saving point?
    I'd appreciate any info on this, as have read the documentation and couldn't find any info on it.
    Cheers,
    Caroline

    We are faced the same problem.
    So I wrote a script that syncs ACLs of the files and folders they're in only if differs.
    I use SQL script that generates ifsshell script and then it is run from the client. See below
    The content of aclsync.sql :
    set serveroutput on size 1000000
    set feed off
    set term off
    spool aclsync.txt
    begin
         dbms_output.put_line('login system/manager');
         for X in (     select
                                       I.object_id, F.acl_id
                                  from
                                       ifs_folder_items I,
                                       ifs_folders F
                                  where
                                            I.folder_id = F.folder_id
                                  and     I.type = 'DOCUMENT'
                                  and     F.acl_id != I.acl_id) loop
              dbms_output.put_line('setattr -id '||X.object_id||' acl -avid '||X.acl_id);
         end loop;
    dbms_output.put_line('exit');
    end;
    spool off
    set term on feed on
    exit
    And the content of the batch file that calls above mentioned script and executes its output
    sqlplus -s ifssys/ifssys@IFS @aclsync
    set PATH=%PATH%;C:\"Program Files"\Oracle\"Oracle 9iFS CmdLine"
    ifsshell -i aclsync.txt
    Anyway
    I'd appreciate some automatic way of doing that.
    Regards Vladimir
    ---

  • Script for checking hardware failures on Solaris

    Hi all,
    I am trying to write a script that checks failures/faults on the Solaris servers(8/9/10) using commands prtdiag -v, echo | format,metastat errors and iostat errors .
    Does anyone have scripts like that?
    Cheers

    please share the script...It doesn't work that way.
    These are technical forums, not replacements for you doing your own work.
    People will be happy to respond with suggestions when you show what you have done but you need to display that you have done some effort first. You have not pasted any of your script here so no one can suggest any improvements to your work.
    Go read the first two replies. They give you a lot of possibilities.

  • Script that adds objects every 2ft.

    Hi,
    So I need to make a script that adds an object every 2 feet around the perimeter of the page.
    I really just have no idea how to start. If anyone could point me in the right direction, or show me an example of something similar being done, that would be awesome!
    This is what I have so far:
    if (x2 >= 96 || y2 >= 96) { /* If x or y are longer than 8 Feet (96 inches) */   
        var x = x2/24;
        while (x > 36 && x < 24) { /* Objects need to be added every 2 to 3 feet */
            x /= 24;
        var y = y2/24;
        while (y > 36 && y < 24) { /* Objects need to be added every 2 to 3 feet */
            y /= 24;
    What I've been thinking (and what I have) is to get some fixed amount between 2 to 3 feet. Then I divide the total x or total y by that fixed amount, and that tells me how many objects I'll need to add.
    I feel like I'm heading on the right track, but making the elements seems to be the most challenging part. I have a function that makes the element I need, and the function is formatted like this: addCircle(page, top, left, bottom, right);
    Any help would be greatly appreciated! Thanks.
    EDIT:
    I have come up with a solution! (somewhat)
    So far it only does one side, but this works:
    var x = x2/24;
    while (x > 36 && x < 24) {
        x /= 24;
    x = Math.round(x);
    var stride = (x2/x);
    for (var i = 0; i <= x; i++) {
        if (i == 0) {
            addCircle (myPage, 0.25, stride*i + 0.25, 0.5, stride*i + 0.5);
        } else if (i == x) {
            addCircle (myPage, 0.25, stride*i - 0.25, 0.5, stride*i);
        } else {
            addCircle (myPage, 0.25, stride*i, 0.5, stride*i + 0.25);

    It seems you are on the right track, but I'm a really curious sort of person.
    How BIG are these 'pages' when you are going to have more than a single object on each side, spaced apart by 61cm!?

  • How to check from a shell script that a particular software is installed

    Hai friends
    I want to write a shell script which has to check whether a particular software is installed on the machine, or not. If installed, then what version is it using and the get the version number and which type of installer is it? i mean is it a .rpm installation or a tar.gz installation.
    how can i check this from a shell script. If any of you have any idea please give me a sample script to check this
    Thank you

    @Raja_Abilash
    I don't think this is a right thread & right forum to POST this question.
    better go ahead with forums related to LINUX.

  • How can I autorun a script that will process an XML file on open?

    I am using Frame 11. I have a registered script that looks for event notification Constants.FA_Note_PostOpenXML. When this event fires, the script is supposed to examine the root element (so I only edit appropriate XML files), then make some edits to the file. Specifically, I want to be able to delete empty pages, remove room for side heads, and fix table formatting (such as left indent, which I can't directly access, apparently, in the EDD or R/W rules). The snippet of code that starts doing the work follows:
    Notification(Constants.FA_Note_PostOpenXML,true);
    function Notify(note, object, sparam, iparam) {
        switch (note) {
            case Constants.FA_Note_PostOpenXML:
                doTheWork();
                break;
    function doTheWork() {
        var doc, flow, root, elemName, mPageAttrib, topicElem, topicElemName, allAttribs;
        doc = app.ActiveDoc;
        flow = doc.MainFlowInDoc;
        root = flow.HighestLevelElement; // will always get something even if unstructured document
        while(root.ObjectValid()) { //only do something for structured docs
            elemName = getElementName(root);
            ...more code to do stuff....
    I then check the root element name, and if it matches, I make some changes. This code works fine when run manually. But, when run as a registered script, the app.ActiveDoc object is invalid, and there is no structure to edit. (I added debug line if(!doc.ObjectValid()){alert("not valid");}, which is not included above.) It appears that the Constants.FA_Note_PostOpenXML event fires as soon as the XML file is opened, but BEFORE Frame actually reads it.
    Does anyone have any recommendations on how to work around this? Is there another event I could use instead of Constants.FA_Note_PostOpenXML? Is there any other way to automatically manipulate an XML file when it loads?
    Thanks in advance

    The Notify event receives four parameters: note, object, sparam, and iparam. For the event you are using, object should be the document object of the FrameMaker document being opened. So, you should be able to use this:
    doTheWork(object);
    Make sure you update your doTheWork function to receive the Doc object:
    function doTheWork(doc) {
        var flow, root, elemName, mPageAttrib, topicElem, topicElemName, allAttribs;
        flow = doc.MainFlowInDoc;
        root = flow.HighestLevelElement; // will always get something even if unstructured document
        while(root.ObjectValid()) { //only do something for structured docs
            elemName = getElementName(root);
            ...more code to do stuff....
    -Rick

  • Need a VB-Script that read a txt-file and only the lines that are new since last time

    Hi,
    I need help to write a VB script that read all new lines since the last time.
    For example:  The script reads the textfile at specific time, then 10 minutes later the script read the file again, and it should now only read the lines that are new since last time. Anyone that has such a script in your scriptingbox?
    cheers!
    DocHo
    Doc

    Based on the excellent idea by Pegasus, where is a VBScript solution. I use a separate file to save the last line count read from the file, then each time the file is read I update the line count. Only lines after the last count are output by the program:
    Option Explicit
    Dim strFile, objFSO, objFile, strCountFile, objCountFile, strLine, lngCount, lngLine
    Const ForReading = 1
    Const ForWriting = 2
    Const OpenAsASCII = 0
    Const CreateIfNotExist = True
    ' Specify input file to be read.
    strFile = "c:\Scripts\Example.log"
    ' Specify file with most recent line count.
    strCountFile = "c:\Scripts\Count.txt"
    ' Open the input file for reading.
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(strFile, ForReading)
    ' Check if the line count file exists.
    If (objFSO.FileExists(strCountFile) = False) Then
        ' Initial count is 0, so all lines are read.
        lngCount = 0
    Else
        ' Open the line count file.
        Set objCountFile = objFSO.OpenTextFile(strCountFile, ForReading)
        ' Read the most recent line count.
        Do Until objCountFile.AtEndOfStream
            lngCount = CLng(objCountFile.ReadLine)
        Loop
    End If
    ' Read the input file.
    lngLine = 0
    Do Until objFile.AtEndOfStream
        ' Count lines.
        lngLine = lngLine + 1
        strLine = objFile.ReadLine
        If (lngLine >= lngCount) Then
            ' Output the line.
            Wscript.Echo strLine
        End If
    Loop
    ' Close all files.
    objFile.Close
    If (lngCount > 0) Then
        objCountFile.Close
    End If
    ' Ignore last line of the file if it is blank.
    If (strLine = "") Then
        lngLine = lngLine - 1
    End If
    ' Save the new line count.
    Set objCountFile = objFSO.OpenTextFile(strCountFile, _
        ForWriting, CreateIfNotExist, OpenAsASCII)
    objCountFile.WriteLine CStr(lngLine + 1)
    objCountFile.Close
    Richard Mueller - MVP Directory Services

  • Script for checking Reader version?

    Does anyone have a script that will check the user's version when opening the form, and throw an error if it is earlier than a specified version?
    Thanks!
    Angie

    Angie,
    If you are referring to the user's version of Reader or Acrobat, you can use xfa.host.version.
    See 'Which Version of Reader?" at http://blogs.adobe.com/livecycle/adobe_livecycle_es/adobe_livecycle_designer_es/
    Steve

  • I need a script that will find the computer a user last logged into.

    I am still learning scripting, I need a script that will allow me to pull in usernames from a csv file. Find what computer they last logged into and output that to an csv file.
    I have looked all over and can't find exactly what I need.
     I found the following script but I need  to add the resuitsize unlimited but can not figure out where to put it we have a large environment. Also I need to be able to grab username from a csv file. Any assistance you can provide is appreciated.
    ##  Find out what computers a user is logged into on your domain by running the script
    ##  and entering in the requested logon id for the user.
    ##  This script requires the free Quest ActiveRoles Management Shell for Active Directory
    ##  snapin  http://www.quest.com/powershell/activeroles-server.aspx
    Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
    $ErrorActionPreference = "SilentlyContinue"
    # Retrieve Username to search for, error checks to make sure the username
    # is not blank and that it exists in Active Directory
    Function Get-Username {
    $Global:Username = Read-Host "Enter username you want to search for"
    if ($Username -eq $null){
    Write-Host "Username cannot be blank, please re-enter username!!!!!"
    Get-Username}
    $UserCheck = Get-QADUser -SamAccountName $Username
    if ($UserCheck -eq $null){
    Write-Host "Invalid username, please verify this is the logon id for the account"
    Get-Username}
    get-username resultsize unlimited
    $computers = Get-QADComputer | where {$_.accountisdisabled -eq $false}
    foreach ($comp in $computers)
    $Computer = $comp.Name
    $ping = new-object System.Net.NetworkInformation.Ping
      $Reply = $null
      $Reply = $ping.send($Computer)
      if($Reply.status -like 'Success'){
    #Get explorer.exe processes
    $proc = gwmi win32_process -computer $Computer -Filter "Name = 'explorer.exe'"
    #Search collection of processes for username
    ForEach ($p in $proc) {
    $temp = ($p.GetOwner()).User
    if ($temp -eq $Username){
    write-host "$Username is logged on $Computer"

    If you are querying by user "resultset size" will be of no use.
    You also have functions that are never used and the body code doe snot look for users.
    Here is what you scrip looks like if printed well.  It is just a jumble of pasted together and unrelated items.
    ## Find out what computers a user is logged into on your domain by running the script
    ## and entering in the requested logon id for the user.
    ## This script requires the free Quest ActiveRoles Management Shell for Active Directory
    ## snapin http://www.quest.com/powershell/activeroles-server.aspx
    Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
    $ErrorActionPreference = "SilentlyContinue"
    # Retrieve Username to search for, error checks to make sure the username
    # is not blank and that it exists in Active Directory
    Function Get-Username {
    $Global:Username = Read-Host "Enter username you want to search for"
    if ($Username -eq $null) {
    Write-Host "Username cannot be blank, please re-enter username!!!!!"
    Get-Username
    $UserCheck = Get-QADUser -SamAccountName $Username
    if ($UserCheck -eq $null) {
    Write-Host "Invalid username, please verify this is the logon id for the account"
    Get-Username
    get-username resultsize unlimited
    $computers = Get-QADComputer | where { $_.accountisdisabled -eq $false }
    foreach ($comp in $computers) {
    $Computer = $comp.Name
    $ping = new-object System.Net.NetworkInformation.Ping
    $Reply = $null
    $Reply = $ping.send($Computer)
    if ($Reply.status -like 'Success') {
    #Get explorer.exe processes
    $proc = gwmi win32_process -computer $Computer -Filter "Name = 'explorer.exe'"
    #Search collection of processes for username
    ForEach ($p in $proc) {
    $temp = ($p.GetOwner()).User
    if ($temp -eq $Username) {
    write-host "$Username is logged on $Computer"
    I suggest finding the original code then use the learning link at the top of this page to help you understand how it works in Powershell.
    ¯\_(ツ)_/¯

  • UCCX8 - script that reads XML file failing, used to work fine in UCCX 5 and 7

    I have a existing script that I've used many times before to read a simple XML file to check open hours for a queue. In both UCCX 5 and 7
    I loaded up all my same scripts, documents , structure, etc..
    When I run script I get the below error.
    The error implies its a security problem but I also wonder if it could simply be a incorrect directory structure as well
    I have the document located in the repository under en\GlobalDocuments\HolidayDatesWithHours.xml
    Is there a differnet way we need to reference documents in UCCX 8 than 5 or 7
    I think I doing it correctly, using the CreateFileDocument and CreateXMLDocument steps, NOT trying to access the filesystem directly
    Do I need to use forward slashes in the file path for UCCX 8 ,
    Any ideas where to look.  This same error appears wherever in my script that I'm trying to read a XML file. different scripts as well so it seems that I'm doing something consistently wrong that used to work correctly on multiple UCCX 5&7 servers in the past.
    Thanks.
    <ERROR>
    527258: Aug 23 14:19:36.635 CDT %MIVR-SECURITY_MGR-2-SECURITY_VIOLATION:Security violation: Permission Name=.\documents\user\en\GlobalDocuments\\HolidayDatesWithHours.xml,Permission Action=read,Application=TrainingQueue,Script=CoreBTS-QueueScript.aef,Step id=437,Step Class=com.cisco.wfframework.obj.WFBeanStep,Step Description=boolTrueFalse = objFile.exists(),Expression=null,Exception=java.security.AccessControlException: access denied (java.io.FilePermission .\documents\user\en\GlobalDocuments\\HolidayDatesWithHours.xml read)
    </END ERROR>

    It should be fine, I assume you mean to reference the full location of your files such as:
    DOC[en\GlobalDocuments\HolidayDatesWithHours.xml]
    Or you could use a document variable such as:
    docVariable = DOC[en\GlobalDocuments\HolidayDateWithHours.xml]
    then in the script reference that:
    doc = Create XML Document (docVariable)

  • Speeding up LabVIEW scripts generated by IMAQ Vision Builder

    Hi,
    I am an experienced c++ software developer, I have mainly used Microsoft's Visual Studio for development. Now, I am developing a real time application using LabView and IMAQ Vision Builder. The LabView application I developed calls a script that was generated by IMAQ vision builder...the application works, but it is too slow for the processing I need to do. In C++ I wouldn't have any trouble speeding the application up, but I am still learning how labview handles threads etc. Does anyone have any ideas?

    Your question is very difficult to answer. Without knowing anything about the processing you are doing, I can't suggest anything to increase the speed.
    Vision Builder does not produce the most efficient code possible. It is likely that the algorithm could be improved, but this really depends on what you are doing. It is also possible that your acquisition could be what is slowing you down, especially if you are using Snap.
    Perhaps if you post the code generated by Vision Builder it will be possible to help you more.
    Bruce
    Bruce Ammons
    Ammons Engineering

  • Script that enables mail users and kicks out two csv files

    I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command. 
    But before it calls that command it will get for various issues that can cause errors.
    Missing PrimarySMTP
    Display name having a space at front or back.
    The external email address being blank.
    I have IF statements setup to check for those and then call a function that will save into an array the issue for that user. 
    Here is the script
    <#
    .SYNOPSIS
    Enable-MailUsers Synced Mail Users in the Exchange environment
    THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
    RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
    Version .9, 30 June 2014
    .DESCRIPTION
    This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled.
    The following is shown:
    * Report Generation Time
    .PARAMETER SendMail
    Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
    .PARAMETER MailFrom
    Email address to send from. Passed directly to Send-MailMessage as -From
    .PARAMETER MailTo
    Email address to send to. Passed directly to Send-MailMessage as -To
    .PARAMETER MailServer
    SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
    .PARAMETER ScheduleAs
    Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
    .EXAMPLE
    Generate the HTML report
    .\Enable-MailUsers.ps1 -SendMail -MailFrom [email protected] -MailTo [email protected] -MailServer ex1.contoso.com -ScheduleAs SvcAccount
    #>
    param(
    [parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
    [parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
    [parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
    [parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
    [parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
    # Sub Function to neatly update progress
    function _UpProg1
    param($PercentComplete,$Status,$Stage)
    $TotalStages=5
    Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
    #Sub Function create ErrObject output
    function _ErrObject{
    Param($name,
    $errStatus
    If(!$err){
    Write-Host "error detected"
    $script:err = $True
    $ErrObject = New-Object -TypeName PSObject
    $Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
    $Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
    $script:ErrOutput += $ErrObject
    # 1. Initial Startup
    # 1.0 Check Powershell Version
    if ((Get-Host).Version.Major -eq 1)
    throw "Powershell Version 1 not supported";
    # 1.1 Check Exchange Management Shell, attempt to load
    if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
    if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
    . 'D:\Exchsrvr\bin\RemoteExchange.ps1'
    Connect-ExchangeServer -auto
    } elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
    Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
    .'D:\Exchsrvr\bin\Exchange.ps1'
    } else {
    throw "Exchange Management Shell cannot be loaded"
    # 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
    if ($SendMail)
    if (!$MailFrom -or !$MailTo -or !$MailServer)
    throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
    # 1.3 Check Exchange Management Shell Version
    if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
    $E2010 = $false;
    if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
    Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
    }else{
    $E2010 = $true
    $localserver = get-exchangeserver $Env:computername
    $localversion = $localserver.admindisplayversion.major
    if ($localversion -eq 15) { $E2013 = $true }
    #Get date
    $filedate = get-date -uformat "%m-%d-%Y"
    $filedate = $filedate.ToString().Replace("0", "")
    #Get the valid users that are not mail-enabled
    _UpProg1 1 "Getting User List" 1
    #$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}
    $i = 0
    $output = @()
    $errOutput = @()
    $err = $False
    #2 Process users
    ForEach ($User in $Users){
    $i++
    _UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
    If ($user.ExternalEmailAddress -eq $null){
    _ErrObject $user.Name, "Missing External Email Address"
    ElseIf($user.DisplayName -NotLike "* "){
    _ErrObject $user.Name, "DisplayName contains a trailing space"
    ElseIf($user.DisplayName -NotLike "_*"){
    _ErrObject $user.Name, "DisplayName contains a Leading space"
    ElseIf($user.PrimarySmtpAddress -eq $null){
    _ErrObject $user.Name, "Missing Primary SMTP address"
    Else{
    #Disable EmailAddressPolicy on these users
    Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
    #pass to Update-recipient
    Update-Recipient $User.Name
    $LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
    If ($LEDN -ne ""){
    $object = New-Object -TypeName PSObject
    $X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
    $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
    $object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
    $output += $object
    #Creating CSVFile Output
    _UpProg1 99 "Outputting CSV file 3" 3
    $CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
    If($err){
    $ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
    $errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
    $Output | ConvertTo-Csv -NoTypeInformation > $CSVFile
    if ($SendMail)
    _UpProg1 95 "Sending mail message.." 4
    If($err){
    Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    Else{
    Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    if ($ScheduleAs)
    _UpProg1 99 "Attempting to Schedule Task.." 4
    $dir=(split-path -parent $myinvocation.mycommand.definition)
    $params=""
    if ($SendMail)
    $params+=' -SendMail:$true'
    $params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
    $task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
    Write-Output "Attempting to schedule task as $($ScheduleAs)..."
    Write-Output "Task to schedule: $($task)"
    schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
    The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.
    Jeff C

    Hi Jeff,
    Any updates? If you have any other questions, please feel free to let me know.
    A little clarification to the script:
    function _ErrObject{
    Param($name,
    $errStatus
    If(!$err){
    Write-Host "error detected"
    $script:err = $True
    $ErrObject = New-Object -TypeName PSObject
    $Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
    $Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
    $script:ErrOutput += $ErrObject
    $errOutput = @()
    _ErrObject Name, "Missing External Email Address"
    $errOutput
    _ErrObject Name "Missing External Email Address"
    $errOutput
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • Script that will show the character count of all carriage resturns

    I have found a bug when exporting an indd to idml. If a a carriage return falls in a character count that is a multiple of 8000 + 1 it is converted to a paragraph separator (u2029). I am in the process of mass exporting around 3000 files to idml for a project. I am trying to come up with a way with a script to check the files to see if carriage returns exist in these locations. I am fairly new to scripting and don't know how this would be done. I know it is possible to get character counts but is it possible to check if a character exists in a certain character count from the beginning of a story? Any help on this would be appreciated.
    Also has anyone else ran into this with exporting to idml? I have submitted a bug report. This is can be recreated across multiple computers, OS's and versions of InDesign.

    @Blujely – about your initial question about showing a specific character at an n-th position in a story, you could use a simple GREP search in InDesign and restrict that search to a specific story (e.g. the story of a selected piece of text):
    Search for the n-th position with the formular in dummy-syntax:
    Positive look behind of any character in the exact length n-1 + character
    E.g. if you want to look for a "carriage return", defined in GREP as \n at every 10th position, search for:
    (?<=.{9})\n
    In your case that would be:
    (?<=.{8000})\n
    Uwe

  • Need a windows script to check all unix db boxes are pinging ?

    Hi ,
    I need a windows script to check all unix remote db boxes are pinging ?
    I need to show the output in an html file.
    Can anyone suggest ideas ?

    I have a script that "kind of" works. The only problem I've seen is that it gets confused when filenames contain characters that are fine in Macland but not good in Unixland. Forward slashes are a good example of this.
    In this case I have a folder in my home named "copytest" Inside copytest are two folders:
    Source (containing the images to be added)
    Dest (My existing library of images)
    It also assumes that the folder of images to be added contains no sub-folders. Hope this helps.
    tell application "Finder"
    set theSource to folder "source" of folder "copytest" of home
    set imagesToBeCopied to name of every file of theSource
    end tell
    repeat with theFile in imagesToBeCopied
    try
    if (do shell script "find -r ~/copytest/dest -name " & quoted form of (theFile as string)) is not equal to "" then
    --The file exists. Don't copy it
    else
    --the file doesn't already exist. Copy it.
    end if
    on error
    return "Failed while trying to check for existence of a file"
    end try
    end repeat

Maybe you are looking for