Search code examples
powershellpipeline

Remove Command from powershell pipeline


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.


Solution

  • 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
    --------
    {}