Remove command from PowerShell pipeline

If I get you right. Usage AddCommand()

adds a command to the pipeline. This means, for example,

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

      

the following script is called:

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

      

Now, can I change this script to

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

      

without reinitialization $PS

? I haven't found a method like DelCommand

that that removes the last command from the pipeline.

The second question is whether successful execution Invoke()

clears the entire deferred command, leaving the pipeline empty.

+3


source to share


1 answer


Yes, you can. Commands are contained in the CommandCollection Object , which inherit from the collection. To remove the second command and add the third, you can do the following:

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

      

Second question: if I understand you correctly, are you wondering when, after using the Invoke method, the commands are cleared from the CommandCollection and remain empty? No, it is not:



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 want to clear them then run the Clear method on Commands property

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

Commands
--------
{}

      

+2


source







All Articles