Oplop98
Oplop98

Reputation: 230

How to convert awk match to powershell command?

I am currently running this command on a linux machine to get pods older than 1 day:

kubectl get pod | awk 'match($5,/[0-9]+d/) {print $1}'

I want to be able to run the same command in Powershell. How could I do it?

kubectl get pod output:

        NAME       READY     STATUS      RESTARTS      AGE
        pod-name   1/1       Running     0             2h3m
        pod-name2  1/1       Running     0             1d2h
        pod-name3  1/1       Running     0             4d4h

kubectl get pod | awk 'match($5,/[0-9]+d/) {print $1}' output:

    pod-name2
    pod-name3

Upvotes: 0

Views: 199

Answers (2)

js2010
js2010

Reputation: 27516

Awk might be a little more convenient in this case. You have to prevent the $split array from being spun out in the pipe before where-object. It turns out I can still reference the $split variable in the foreach-object.

'        NAME       READY     STATUS      RESTARTS      AGE
         pod-name   1/1       Running     0             2h3m
         pod-name2  1/1       Running     0             1d2h
         pod-name3  1/1       Running     0             4d4h' | set-content file

get-content file | 
  where-object { $split = -split $_; $split[4] -match '[0-9]+d' } |
  foreach-object { $split[0] }

pod-name2
pod-name3

Upvotes: 0

Paolo
Paolo

Reputation: 26220

You can use:

$long_running_pods=(kubectl get pod | Tail -n+2 | ConvertFrom-String -PropertyNames NAME, READY, STATUS, RESTARTS, AGE | Where-Object {$_.AGE -match "[1-9][0-9]*d[0-9]{1,2}h"})
$long_running_pods.NAME

This will give you all pods which have been running for more than one day.


Example:

$long_running_pods=(echo 'NAME       READY     STATUS      RESTARTS      AGE
pod-name   1/1       Running     0             1d2h
pod-name2  1/1       Running     0             0d0h' | Tail -n+2 | ConvertFrom-String -PropertyNames NAME, READY, STATUS, RESTARTS, AGE | Where-Object {$_.AGE -match "[1-9][0-9]*d[0-9]{1,2}h"})
$long_running_pods.NAME 

will print:

pod-name

Upvotes: 1

Related Questions