Do you know you can encrypt a PowerShell script and run the encrypted script?
Use case: You want to keep the script on a shared path so that it's accessible for running but don't want others to see the code inside. Another benefit, this ties the script to one machine, one user and even though someone can bypass PowerShell executionpolicy, they cannot bypass this and no modification in script would be possible unless you have access to machine and the user credential
?
# It would encrypt the script content using Windows Data Protection API using your user account and machine name. Means it can be decrypted ONLY on the same machine and by the same user account
?
# It would decrypt and run the script ONLY on the same machine and with the same user logged in, through which it was encrypted.
Function Export-EncryptedScript {
[cmdletbinding()]
param (
[parameter(Mandatory=$true, ValueFromPipeline=$True)][validatescript({Test-Path $_})][string]$ScriptPath,
[parameter(Mandatory=$true, ValueFromPipeline=$True)][string]$ExportPath
)
[string]$Code = Get-content -Path $ScriptPath
$SecureCode = ConvertTo-SecureString $Code -AsPlainText -Force
$null = ConvertFrom-SecureString -SecureString $SecureCode | Out-File -FilePath $ExportPath
}
Function Run-EncryptedScript {
[cmdletbinding()]
param (
[parameter(Mandatory=$true, ValueFromPipeline=$True)][validatescript({Test-Path $_})][string]$ScriptPath,
[parameter(Mandatory=$false, ValueFromPipeline=$True)][switch]$ShowOnly
)
[string]$scriptCode = Get-Content $ScriptPath
$decryptedCode = $scriptCode | ConvertTo-SecureString
$Code = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($decryptedCode))
if($ShowOnly){
$Code -split "\t"
} else {
Invoke-Expression $Code
}
}
?
If you are looking to run it with a service account, then just right click PowerShell, run as that user then perform the encryption so that when you call decryption in the same service account context then it can work.
?
PS: If required then the code can be updated so that it doesn't make use of WDPA but of a key file storing 32-byte key. That way it would be portable and can be run from any machine or user.
ICT—Co?rdinator / Azure Systeembeheerder
1 年It's only useful when you're allowed to make an encrypted powershell script that only you can read or execute in/on a company's network that allows you to do that. Unfortunately....., I could not think of such situation. As a matter of fact, it would give them a reason to fire my position as system administrator.