Run ScriptBlock with different credentials

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   = '[email protected]'
$Password   = ConvertTo-SecureString -String $password -AsPlainText -Force
$Credential = New-Object -Type PSCredential($Username,$Password)
$Session    = New-PSSession -Credential $Credential

Invoke-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!


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.