2

I have an array of computer names, $computers, that are in a FQDN format. I want to trim all characters to the right of the first period and including the period.

Ex: server-01.mydomain.int = server-01

This is what I tried but it errors out.

$computers = Get-VM | Select Name
$computers = $computers.Substring(0, $computers.IndexOf('.'))
$computers

2 Answers 2

3

When you do |Select Name, PowerShell returns an object with a Name property, rather than only the value of each Name property of the input objects.

You could change it to Select -ExpandProperty Name and then iterate over each item in the array for the actual substring operation using a loop or ForEach-Object - although we can skip the first step completely:

$computers = Get-VM |ForEach-Object { $_.Name.Substring(0, $_.Name.Indexof('.')) }
Sign up to request clarification or add additional context in comments.

2 Comments

@Steve Forgot the Name property in the second function call, updated now
Thank you very much! The output is exactly what I was looking for.
0

Or another way.

$computers = Get-VM | ForEach-Object { ($_.Name -split ".")[0] }

Since you are always selecting the first string before the first "." you can just split at the dot and select the first element in the resulting array.

Comments

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.