【问题标题】:How to pass string variable to invoke-expression?如何将字符串变量传递给调用表达式?
【发布时间】:2014-08-15 12:02:28
【问题描述】:

我正在运行以下 powershell 命令:

$cmd = "xxx.exe"

Invoke-Command -ComputerName localhost {Invoke-Expression $cmd}

但是我得到了错误:

Cannot bind argument to parameter 'Command' because it is null.

+ CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterB
indingValidationException
 + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.PowerShell.Commands.InvokeExpressionCommand

【问题讨论】:

    标签: powershell invoke-command


    【解决方案1】:

    查看Invoke-Command 的文档。

    使用 -ArgumentList 参数,或者如果 powershell 3 参见示例 9 ($Using:)。

    http://technet.microsoft.com/en-us/library/hh849719.aspx

    ArgumentList 示例 -

    $cmd = "xxx.exe"
    Invoke-Command -ComputerName localhost {Invoke-Expression $args[0]} -ArgumentList $cmd
    

    如果您在脚本块中使用param,您可以使用命名参数而不是$args 内置。

    【讨论】:

    • 你能告诉我如何在我的情况下使用 ArgumentList 吗?我尝试了几种方法,但没有成功。谢谢。
    【解决方案2】:

    我将向您展示我的做法,使用-FilePath 传递文件并使用-ArgumentList 传递参数

    我创建了一个函数,它将包含我要执行的代码。

    #remote_functions.ps1
    param($command, $param1, $param2, $param3, $param4, $param5)
    $ScriptVersion = "1.0"
    
    function Write5Strings($string1, $string2, $string3, $string4, $string5)
    {
        Write-Host "String1: $string1"
        Write-Host "String2: $string2"
        Write-Host "String3: $string3"
        Write-Host "String4: $string4"
        Write-Host "String5: $string5"
        throw "ERROR"
    }
    
    
    try
    {
        &$command $param1 $param2 $param3 $param4 $param5
    }
    catch [System.Exception]
    {
        Write-Error $_.Exception.ToString()
        exit 1
    } 
    

    我这样调用它:

    $server="server"
    $remotingPort=81
    
    $job = Invoke-Command -AsJob -Port $remotingPort -ComputerName $server -FilePath ".\remote_functions.ps1" -ArgumentList @("Write5Strings", "apple", "banana", "orange", "pear", "watermelon")
    

    还要检查这个问题:How do I pass named parameters with Invoke-Command?

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 1970-01-01
      • 2019-07-13
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2016-08-05
      相关资源
      最近更新 更多