3

我正在尝试使用 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

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

Remove-Item -LiteralPath $path -Force -Credential $cred

有任何想法吗?

4

2 回答 2

6

我不清楚这些文件是本地的(您在服务器上运行脚本)还是远程的(在另一台机器上)。如果本地尝试使用后台作业运行命令并将凭据传递给 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

注意:这需要您在远程机器上执行 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 
于 2010-06-18T01:51:01.213 回答
0

由于授权,Remove-Item 可能会失败。或者,找到每个文件的引用并使用 .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 
}
于 2016-12-08T06:56:52.157 回答