Steve
Steve

Reputation: 21

How to remove characters from an item in an array using PowerShell

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

Upvotes: 2

Views: 4698

Answers (2)

Parrish
Parrish

Reputation: 177

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.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

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('.')) }

Upvotes: 3

Related Questions