将Powershell变量传递到scriptblock中

时间:2011-08-11 08:36:08

标签: blackberry powershell remoting

我正在尝试使用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

我正在运行

  

。\ 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 Resource Kit \ BlackBerry Enterprise Server用户管理工具客户端“       + CategoryInfo:InvalidArgument:(:) [Invoke-Command],ParameterBindingException       + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand

感谢阅读,欢呼科尔姆。

1 个答案:

答案 0 :(得分: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

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

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