将Remove-Item与凭证一起使用

web*_*1ar 3 powershell cmdlets powershell-2.0

我试图使用Remove-Item cmdlet作为系统自动化的一部分.这些文件存储在需要提升权限才能执行文件删除的服务器上.我可以访问用于此类自动化脚本的域管理员帐户.

下面的代码将构建PSCredential对象:

$password = New-Object System.Security.SecureString
"passwordhere".ToCharArray() | ForEach-Object { $password.AppendChar($_) }
$cred = New-Object System.Management.Automation.PSCredential("domain\username",$password)
$cred
Run Code Online (Sandbox Code Playgroud)

我将此对象传递给以下操作:

Remove-Item -LiteralPath $path -Force -Credential $cred
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Kei*_*ill 6

我不清楚文件是本地的(您在服务器上运行脚本)还是远程(在另一台机器上).如果本地尝试使用后台作业运行该命令并将凭据传递给Start-Job:

$job = Start-Job { Remove-Item -LiteralPath $path -force } -cred $cred 
Wait-Job $job
Receive-Job $job
Run Code Online (Sandbox Code Playgroud)

如果他们是远程的,请尝试使用远程处理:

Invoke-Command -computername servername `
               -scriptblock { Remove-Item -LiteralPath $path -force } `
               -Cred $cred
Run Code Online (Sandbox Code Playgroud)

注意:这要求您在远程计算机上执行Enable-PSRemoting.

通常,将原始密码放在脚本中并不是一个好主意.您可以使用DPAPI以加密方式存储密码,稍后,只有该用户帐户才能解密密码,例如:

# Stick password into DPAPI storage once - accessible only by current user 
Add-Type -assembly System.Security 
$passwordBytes = [System.Text.Encoding]::Unicode.GetBytes("Open Sesame") 
$entropy = [byte[]](1,2,3,4,5) 
$encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect( ` 
                       $passwordBytes, $entropy, 'CurrentUser') 
$encrytpedData | Set-Content -enc byte .\password.bin 

# Retrieve and decrypted password 
$encrytpedData = Get-Content -enc byte .\password.bin 
$unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( ` 
                       $encrytpedData, $entropy, 'CurrentUser') 
$password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) 
$password 
Run Code Online (Sandbox Code Playgroud)