【问题标题】:Invoke powershell cmdlet dynamically with object parameter values使用对象参数值动态调用 powershell cmdlet
【发布时间】:2014-05-22 15:32:31
【问题描述】:

我已经创建了自定义 PowerShell cmdlet,并且正在为它们编写测试脚本。

我得到了 cmdlet 的列表,我必须向它传递一个非字符串类型的对象。我尝试使用 Invoke-Expression,但在使用字符串名称作为参数值时出现错误。

$cmd = @()
$cmd += Get-Cmdlet1
$cmd += Get-Cmdlet2
$cmd += Get-Cmdlet3
foreach($c in $cmd)
{   
    $ret1 =  $c + " -connection "
    $ret = Invoke-Expression "$ret1 $($conn)"
    $ret >> C:\Output.txt
}

$conn 是自定义 SSH 连接对象(不是 PowerShell 对象类型)。 我得到了错误

Invalid input: System.String is not supported
Parameter name: Connection

如何调用这样一个动态添加名称和对象参数的命令?

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    试试这样:

    $cmd = @()
    $cmd += Get-Command Get-Cmdlet1
    $cmd += Get-Command Get-Cmdlet2
    $cmd += Get-Command Get-Cmdlet3
    foreach($c in $cmd)
    {   
        &$c -connection $conn >> C:\output.txt
    }
    

    如果您将$conn 放在双引号字符串中,PowerShell 会将该对象转换为字符串。此外,这个$cmd = Get-Cmdlet1 执行Get-Cmdlet1。不确定这是否是您想要的,因为您似乎想在 foreach 循环中执行 cmdlet。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2013-06-08
      • 1970-01-01
      • 2010-12-05
      • 2023-04-10
      相关资源
      最近更新 更多