使用对象参数值动态调用powershell cmdlet

时间:2014-05-22 15:32:31

标签: c# powershell

我已经创建了自定义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

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

1 个答案:

答案 0 :(得分:3)

试试这样:

$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。