1

我编写了一个脚本,它为我提供了用户/组的文件夹 + 子文件夹的所有权限。但是,该脚本仅在我的用户至少对所有这些文件夹具有读取权限的情况下才有效。如果他没有权限,get-acl 将被拒绝。有什么办法可以解决这个问题,因为我不想在每次执行这个脚本时手动切换我的用户。

我可以使用其他用户执行 powershell 脚本吗?如果是,如何?

提前谢谢你,科林

4

1 回答 1

2

你有几个我能想到的选择:

选项 1:使用您要运行的实际代码创建一个帮助文件,并将其命名为 script.ps1,例如:

    [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
    }

选项 2:为每个用户运行一个作业。每项任务完成后,都会询问新的用户凭据。只需将代码添加到脚本块

[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)"
}

希望这可以帮助!

请注意,creds 对象也可以是自动化的,如果您不想一直键入。(未考虑安全原则;))

$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
}
于 2019-11-28T11:18:53.273 回答