資格情報を備えたremove-itemを使用します
-
28-09-2019 - |
質問
私は、システムの自動化の一部として削除項目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
注:これには、リモートマシンで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
他のヒント
承認のために削除項目が失敗する可能性があります。または、各ファイルの参照を見つけて.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