题
我试图将删除项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
我将此对象传递给以下操作:
Remove-Item -LiteralPath $path -Force -Credential $cred
有任何想法吗?
解决方案
我不清楚文件是否是本地(服务器上的脚本)或遥控器(在另一台计算机上)。如果本地尝试使用后台作业运行命令,然后将凭据传递给Start-Job:
$job = Start-Job { Remove-Item -LiteralPath $path -force } -cred $cred
Wait-Job $job
Receive-Job $job
如果它们是遥远的,请尝试使用远程:
Invoke-Command -computername servername `
-scriptblock { Remove-Item -LiteralPath $path -force } `
-Cred $cred
注意:这要求您在远程计算机上执行启用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
其他提示
由于授权,删除项目可能会失败。另外,要么找到每个文件的参考,然后用.delete()将其击中,或将所有文件移至回收箱。
foreach ($svr in $computers)
{
Invoke-Command -ComputerName $svr {
$folderitems = Get-ChildItem $cachefolder -Recurse
# Method 1: .Delete
foreach ($cachefolderitem in $cachefolderitems)
{
if ($cachefolderitem -like "*.ini")
{
$cachefolderitem.Delete()
}
}
# Method 2: Move all matching files to the recycle bin
Move-Item "$cachefolder\*.ini" 'C:\$Recycle.Bin' -Force
}
不隶属于 StackOverflow