Search code examples
powershellpermissionsactive-directorycredentialsfolder-permissions

Powershell Get-Acl for folders without access permissions


I wrote a script, which gives me all the permissions of a folder + subfolders for a user/group. However, the script only works, if my user has at least read permissions on all these folders. If he has no permissions, get-acl is denied. Is there any way to work around this, as I don't want to manually switch my user everytime I execute this script.

Can I execute a powershell script with a different user? And if yes, how?

Thank you in advance, Colin


Solution

  • You have a few options that I can think of:

    Option 1: Create a helper file with the actual code you want to run and call it script.ps1 for instance:

        [array]$users = "user1","user2","user3"
    
        foreach($user in $users){
            $creds = Get-Credential -UserName $user -Message "Enter the Users Password"
            $Session = New-PSSession -Credential $creds
            Invoke-Command -Session $Session -FilePath C:\Path\to\some\script.ps1
        }
    

    Option 2: Run a job for each user. After every task is finished, the new user credentials will be asked. Just add the code to the scriptblock

    [array]$users = "user1","user2","user3"
    
    foreach($user in $users){
        $creds = Get-Credential -UserName $user -Message "Enter the Users Password"
        $target = $user
        $job = Start-Job -scriptblock {
        param ($username)
            Get-Acl C:\Users\$user #Bla bla the rest of your script
        } -Args $user -credential $creds
        do{
            #Wait for the job to finish
        }until($job.State -ne "Running")
        Write-Host "Job finished with state $($job.State)"
    }
    

    Hope this helps!

    Note that the creds object can also be automated, if you don't wish to type all the time. (Security principles not taken into account ;) )

    $users = @()
    $users += @{
        username = "User1"
        password = "Pass123!"
    }
    $users += @{
        username = "User2"
        password = "Pass123!"
    }
    
    foreach($user in $users){
        $creds = New-Object System.Management.Automation.PSCredential($user.username,($user.password | ConvertTo-SecureString -AsPlainText -Force))
        #Add the rest of the script from the chosen option
    }