Run ScriptBlock with different credentials
I got it, thanks to Trevor Sullivan for pointing me in the right direction. I ended up just putting my second ps1 file into a scriptblock, and running it as a job, and passing it the arguments from the main script, like this
$job = Start-Job -scriptblock {param ($username)some code to run against the variable that was passed in} -Args $target -credential $Cred
$target being the variable I want to pass to my scriptblock.$username being the parameter that the scriptblock accepts Thanks.
I know this was answered a long time ago, but I thought I'd add another option for those looking that returns data without having to retrieve it.
We can create a helper script that creates a pscredential and then uses it to start a local PSSession to run a script or scriptblock in a different user's context. You need to get the user password from somewhere, preferably entered as a secure string or retrieved from a Key Vault, but for the example our helper script will take it as a string parameter.
Script contents:
param ([string]$username,[string]$password)$Username = 'username@domain.com'$Password = ConvertTo-SecureString -String $password -AsPlainText -Force$Credential = New-Object -Type PSCredential($Username,$Password)$Session = New-PSSession -Credential $CredentialInvoke-Command -Session $Session -FilePath C:\Path\to\some\script.ps1
You can also use -ScriptBlock
instead of -FilePath
if you have a simple chunk of code to run or you have converted a script to a script block.
Hope this helps somebody out!
Security context for a session is established when the session is initialized. You can't arbitrarily run commands under a different context within the session. To run under a different security context (set of credentials) you'll need to initialize a new session under those credentials and run it there.
If you look at the help for Invoke-Command
, you'll note that the -Credential
parameter is only valid in parameter sets that specify a remote session by computername, uri, or session. You can also use -credential
with Start-Job
, which will run the command in a new session on the local machine.