简体   繁体   中英

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.

在此处输入图片说明

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM