3

If I understood correctly. Using AddCommand() adds a command to a pipeline. That means for example

$PS = [PowerShell]::Create()
$PS.AddCommand("Command-One").AddParameter("Param1");
$PS.AddCommand("Command-Two").AddParameter("Param2");
$PS.Invoke();

will invoke following script:

PS> Command-One -Param1 | Command-Two -Param2

Now, can I change this script to

PS> Command-One -Param1 | Command-Three -Param3

without having to reinitialize $PS? I didn't find method like DelCommand that would remove last command from a pipeline.

Second question is whether successful execution of Invoke() cleans out all pending command leaving pipeline empty.

1 Answer 1

2

Yes, you can. The commands are contained in a CommandCollection Object which inherit off of collection. To remove the second command and add the third you could do the following:

$PS.Commands.Commands.RemoveAt(1)
$PS.AddCommand("Command-Three").AddParameter("Param3")

Second question: If I understand you correctly, you are wondering if when after you use the Invoke method, the commands are cleared from the CommandCollection and it is left empty? No, that is not the case:

PS> $PS = [Powershell]::Create()
PS> $PS.AddCommand("New-Item").AddParameter("Name", "File.txt").AddParameter("Type","File")
PS> $PS.AddCommand("Remove-Item").AddParameter("Path", "File.txt")
PS> $PS.Invoke()
PS> $PS.Commands

Commands
--------
{New-Item, Remove-Item}

If you would like to clear them, run the Clear method on Commands property

PS> $PS.Commands.Clear()
PS> $PS.Commands

Commands
--------
{}
1
  • 1
    Your answer was more than perfect. Huge +
    – Mike
    Aug 6, 2014 at 11:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.