将Powershell变量传递到scriptblock中

Col*_*ake 12 powershell remoting blackberry

我正在尝试使用powershell变量并将它们应用于scriptblock.

param(
    [string]$username = $(throw "Blackberry Admin User Name is required"),
    [string]$password = $(throw "Blackberry Admin Password is required"),
    [string]$u = $(throw "Blackberry User Name is required")
    )

$s = New-PSSession -computerName bbbes01 
Invoke-Command -Session $s -Scriptblock {cd "C:\Program Files (x86)\Research In Motion\BlackBerry Enterprise Server Resource Kit\BlackBerry Enterprise Server User Administration Tool Client"
./BESUserAdminClient -username $username -password $password -ad_auth -domain staging -b bbbes -u $u -change -wrandom} -argumentlist $username $password $u
Run Code Online (Sandbox Code Playgroud)

我在跑步

.\ RandomActivationEmail.ps1 -username besadmin -password Pa $$ word -u bb.user

我得到的错误是: -

Invoke-Command:找不到接受参数'Pa $$ word'的位置参数.在C:\ Scripts\bb\RandomActivationEmail.ps1:12 char:15 + Invoke-Command <<<< -Session $ s -Scriptblock {cd"C:\ Program Files(x86)\ Research In Motion\BlackBerry Enterprise Se rver资源工具包\ BlackBerry Enterprise Server用户管理工具客户端"+ CategoryInfo:InvalidArgument :( :) [Invoke-Command],ParameterBindingException + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand

感谢阅读,欢呼科尔姆.

Sha*_*evy 24

您可以通过-arguments参数传递值,并把它们称作的$ args [0]等脚本块内:

Invoke-Command -Session $s -Scriptblock {
    cd "C:\Program Files (x86)\Research In Motion\BlackBerry Enterprise Server Resource Kit\BlackBerry Enterprise Server User Administration Tool Client"
    ./BESUserAdminClient -username $args[0] -password $args[1] -ad_auth -domain staging -b bbbes -u $args[2] -change -wrandom
} -argumentlist $username $password $u
Run Code Online (Sandbox Code Playgroud)

或者在脚本块中定义参数并使用命名参数:

Invoke-Command -Session $s -Scriptblock {
    param(
        $username,$password,$u
    )

    cd "C:\Program Files (x86)\Research In Motion\BlackBerry Enterprise Server Resource Kit\BlackBerry Enterprise Server User Administration Tool Client"
    ./BESUserAdminClient -username $username -password $password  -ad_auth -domain staging -b bbbes -u $u -change -wrandom
} -argumentlist $username $password $u
Run Code Online (Sandbox Code Playgroud)

  • 固定!感谢Shay让我指向正确的方向--username $ args [0] -password $ args [1] -ad_auth -domain staging -b bbbes -u $ args [2] -change -wrandom} -argumentlist @($ username ,$ password,$ u)在参数列表中使用$ args和@()非常感谢 (3认同)