Vijay
Vijay

Reputation: 167

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?

Upvotes: 0

Views: 777

Answers (1)

Keith Hill
Keith Hill

Reputation: 201832

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.

Upvotes: 3

Related Questions