0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.