Using the Delete Item with Credentials

I am trying to use the Remove-Item cmdlet as part of automation for a system. Files are stored on a server that requires elevated privileges to perform file deletion. I have access to the domain administrator account that I use for such automation scripts.

In the code below, a PSCredential object will be created:

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

I pass this object to the following action:

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

Any ideas?

+3
source share
2 answers

, ( script ) ( ). 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 .

, script . 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 
+6

- - . , , .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 
}
0

Source: https://habr.com/ru/post/1750573/


All Articles