Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Remove-Item with Credentials

I am attempting to use the Remove-Item cmdlet as part of an automation for a system. The files are stored on a server that requires elevated rights to perform the file deletion. I have access to a domain admin account that I use for such automation scripts.

The code below will build the PSCredential object:

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

I am passing this object to the following action:

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

Any ideas?

like image 498
websch01ar Avatar asked Aug 15 '26 17:08

websch01ar


1 Answers

It's not clear to me if the files are local (you're running the script on the server) or remote (on another machine). If local try running the command using a background job and pass in the credentials to Start-Job:

$job = Start-Job { Remove-Item -LiteralPath $path -force } -cred $cred 
Wait-Job $job
Receive-Job $job

If they're remote, try using remoting:

Invoke-Command -computername servername `
               -scriptblock { Remove-Item -LiteralPath $path -force } `
               -Cred $cred

Note: This requires that you execute Enable-PSRemoting on the remote machine.

In general, putting raw passwords in your script isn't a great idea. You can store the password in an encrypted manner using DPAPI and later, only that user account can decrypt the password e.g.:

# 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 
like image 144
Keith Hill Avatar answered Aug 17 '26 12:08

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!