Projecting commands in pipeline

Hello

I am new to powershell so apologies in advance if this is a silly question.

I am trying to write a powershell pipeline that will take output from kubectl, project that into a state I can do logic on (filter mostly) and then apply commands to it.

My first pipeline which will cache all the pvc objects (this is essentially just a big json object of which I extract a few fields)

$pvcs = kubectl get pvc -o json | ConvertFrom-Json | select -expand items | select @{N='Name';E={$_.metadata.name}},@{N='Phase';E={$_.status.phase}},@{N='StorageClass';E={$_.spec.storageClassName}}

At this point I have a bunch of objects in $pvcs with the names I want. Piping this to Format-Table looks great.

Now to my problem:

I want to run a kubectl command on every one of these objects, the only way I have been able to generate the command I want to do is via a for loop which produces a string I can throw to the call operator

foreach ($i in $pvcs) {“kubectl delete pod $($i.Name)” }

Is there a more concise way of doing this were I can simply pipe my objects from the first statement into a set of commands that I want to execute?

Thank you for your help

Joakim

I don’t know much about kubectl, but if you are calling an external executable, you should not even need a call operator. If you don’t need anything stored in a variable, you can pipe to Foreach-Object {}

kubectl get pvc -o json | ConvertFrom-Json | Select -expand items |
    Select @{N='Name';E={$_.metadata.name}},@{N='Phase';E={$_.status.phase}},@{N='StorageClass';E={$_.spec.storageClassName}} |
        Foreach-Object { kubectl delete pod $_.Name }

Inside Foreach-Object{}, $_ is the current object passed into the pipeline. So you could continue executing other commands within the script block on that same object if you wish.

This was exactly what I was looking for, thank you so much!

you would wanna have a look at below PowerShell module developed by Jim from PowerShell team as well.

https://www.powershellgallery.com/packages/Microsoft.PowerShell.KubeCtl/0.0.3

PS: PowerShell 7 is a prereq for this