简体   繁体   中英

Invoke powershell cmdlet dynamically with object parameter values

I have created custom PowerShell cmdlets and I am writing a test script for them.

I get the list of cmdlets and I have to pass it an object of non-string type. I tried using Invoke-Expression but I get an error where it uses the string name for the parameter value.

$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 is a custom SSH connection object(not a PowerShell object type). I get the error

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

How can I invoke such a command with name and object parameter added dynamically?

Try it like this:

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

If you put $conn in a double-quoted string, PowerShell will convert that object to a string. Also, this $cmd = Get-Cmdlet1 executes Get-Cmdlet1 . Not sure if that is what you intended as you seem to want to execute the cmdlet inside the foreach loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM