Todd Welch
Todd Welch

Reputation: 1779

How To Pass User Credentials from One Powershell Script to Another?

I have a main menu script where I ask for the user to enter admin credentials and I want to use them in other scripts that the main menu calls.

Here is my call to other scripts which launches the new script just fine and the called script runs.

Start-Process PowerShell.exe -ArgumentList "-noexit", "-command &$ScriptToRun -UserCredential $UserCredential"

In the called script I accept the parameters like this

#Accept User Credentials if sent from Main menu
param(
[parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true,Mandatory=$false)]
  [PSCredential]$UserCredential
)

Instead of accepting the credentials, though, it is launching the prompt asking for credentials with the name of the object in the user field.

enter image description here

Any help would be greatly appreciated in figuring this out, as I am banging my head against the wall.

Upvotes: 4

Views: 2819

Answers (2)

John Rees
John Rees

Reputation: 1813

One simple way to launch a process with credentials is to use Jobs.

$UserCredential = Get-Credential
$ScriptBlock = {param($x) "Running as $(whoami).  x=$x"}
& $ScriptBlock 10          # Just check it works under current credentials
$Job = Start-Job -Credential $UserCredential -ScriptBlock $ScriptBlock -ArgumentList 20
Receive-Job -Job $Job -Wait -AutoRemoveJob

One advantage of using jobs is that you get Output, Error, Verbose and Warning streams passed back to the caller which is not possible when using Start-Process.

When using jobs all arguments and return values are implicitly serialized, which has limitations when passing complex objects, but copes well with all the basic types.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

You can't pass non-string object directly across process boundaries like that, the input arguments to the new process is always going to be bare strings.

What you can do instead is use $UserCredentials to simply launch the new process:

Start-Process PowerShell.exe -Credential $UserCredential -ArgumentList "-noexit", "-command &$ScriptToRun" 

... or, preferably, call Invoke-Command from the calling script instead of starting a new process:

Invoke-Command -ScriptBlock $scriptBlockToRun -Credential $UserCredential

Upvotes: 2

Related Questions