Home > Software engineering >  Windows powershell command, use output from one command directly as parameter in another
Windows powershell command, use output from one command directly as parameter in another

Time:09-07

I would like to have a command that gets the name of a pod and then uses it to log in to the pod. The command to list the pods to get the pod name:

kubectl get pods | Select-String -Pattern "mypodname"

The output is:

mypodname 1/1 Running    0  4d3h

I need to only get the value mypodname here. I have tried with Select-Object NAME with no luck. The podname changes over time. For example it can be mypodname-3467gogsfg one day and mypodname-043086dndn the next day because of new deployment.

This value I will use in this command:

kubectl --server=https://myservername.com --insecure-skip-tls-verify exec -it <name of pod goes here> /bin/sh

The second question is how these two can be combined in a windows powershell script so I can run something like this to log in to the pod:

podlogin mypodname

CodePudding user response:

A function is probably what you're after since you're looking to combine the results into an execution by passing just the name:

Function PodLogin ($PodName) {
    $name = kubectl get pods | ? { $_ -match "(?<=($PodName-.*))\s" } | % { $Matches[1] }
    kubectl --server=https://myservername.com --insecure-skip-tls-verify exec -it $name /bin/sh
}

The use of Where-Object (?) just allows for a more condensed code without having to dig through the properties for the value matched since -Match will populate the $Matches automatic variable. Then, piping to Foreach-Object (%) to access the value matched via $Matches[1]; although not necessarily needed, saving it to a $name is more appealing overall. Finally, pass the $name to your command for execution.

Now you can call it using PodLogin podname.

Here's a RegEx demo that explains the pattern.

  • Assuming the pattern is always podname-.... , which is followed by a space.

CodePudding user response:

If I understand you correctly, you can split the output and then assign the first word to a variable. The output of kubectl is text, not an object.

$podname = -split (kubectl get pods | select-string mypodname) | select -first 1
$podname

mypodname


podlogin $podname
  • Related