[英]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:你可以做的是使用$UserCredentials
来简单地启动新进程:
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
而不是启动新进程:
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.使用作业的优点之一是您将输出、错误、详细和警告流传递回调用者,这在使用 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.使用作业时,所有参数和返回值都被隐式序列化,这在传递复杂对象时有局限性,但可以很好地处理所有基本类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.