如何将 awk 匹配转换为 powershell 命令?

How to convert awk match to powershell command?

我目前 运行 在 linux 机器上执行此命令以获得 pods 超过 1 天:

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

我希望能够 运行 在 Powershell 中执行相同的命令。我该怎么做?

kubectl get pod 输出:

        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(,/[0-9]+d/) {print }' 输出:

    pod-name2
    pod-name3

您可以使用:

$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

这将为您提供已经 运行 超过一天的所有 pods。


示例:

$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 

将打印:

pod-name

在这种情况下,Awk 可能更方便一些。您必须防止 $split 数组在 where-object 之前在管道中旋转。事实证明,我仍然可以在 foreach 对象中引用 $split 变量。

'        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