0
votes

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

1
A lot of options to achieve this. Check out this post: stackoverflow.com/questions/28989750/…Bernard Moeskops
Yes but I wish to execute the script instantly without any more user actions neededAndr0mega
What do you mean by instantly? If you post your code and exactly what you mean it would be easier to help. For my understanding now you should use try catch in order to determine whether a users has permissions or not. So you can catch when the access is denied.Bernard Moeskops
There is no code I can show you. But what I mean is: 1) Script gets executed 2) Asking for Credentials of the user, you want to execute the script with 3) Execute the rest of the script. I don't want to open a new Powershell window. If possible.Andr0mega

1 Answers

1
votes

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
}