0

So I have a HyperV machine, and I can get the IP address thus:

Get-VM -VMName localdev | Select -ExpandProperty Networkadapters | Select -ExpandProperty IPAddresses | Select-Object -First 1

What I can't figure is how to 'pipe' this to SSH to connect to the machine in a single line.

Get-VM ....... | Select-Object -First 1 | ssh 

^^^ this doesn't work.

I can do this but it's lacking in elegance:

$localdevip = Get-VM -VMName localdev | Select -ExpandProperty Networkadapters | Select -ExpandProperty IPAddresses |Select-Object -First 1
ssh $localdevip

Although this works, I want to understand Powershell better. How can I funnel the result from the Select-Object call into the parameter for the command (in the example it's SSH but could be anything) without assigning a variable?

6
  • Is the IP Address just the output? You can use a calculated property to narrow it down to just one Select-Object including the -Fist 1 parameter Commented Aug 10, 2021 at 16:13
  • Yes, it literally outputs only 1.2.3.4 yet if I add | ssh it behaves as though I've passed no parameters and shows the help text. Commented Aug 10, 2021 at 16:19
  • 1
    the posted answer is what i was going to suggest, with a few changes. SSH is not a powershell cmdlet, meaning it does not accept pipeline input. Commented Aug 10, 2021 at 16:27
  • Please, do post an answer if there's a better way that makes it more pure Powershell. I just couldn't figure out where the output vanished to, but I'm coming from a Bash/Linux background where things work differently. Commented Aug 10, 2021 at 16:58
  • 1
    I'd keep the two-liner, because it is easier to debug. Commented Aug 10, 2021 at 17:04

1 Answer 1

1

Try this

ssh (Get-VM -VMName localdev | Select -ExpandProperty Networkadapters | Select -ExpandProperty IPAddresses |Select-Object -First 1)
Sign up to request clarification or add additional context in comments.

1 Comment

Since OP mention "elegeance", this is a bit shorter and might be easer to read and type. ssh (Get-VM -VMName localdev).Networkadapters.IPAddresses[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.