Please explain computer name regex

I found following regex:

[string[]] $Domain = "one or more computer names"

foreach ($Computer in $Domain)
       # Why is this needed?
       $Computer = $Computer -replace '(.*?)\..+', '$1'

Why is this regex necessary for computer name and what it does?

An easy way to get explanations for regex and even to test it by yourself is

In this case the regex is looking for
(.*?) a group of zero or more of any character (the question mark makes the pattern non greedy)
\. a literal point
.+ 1 or more of any character

and the replace part takes the first found goup from the pattern to replace what’s the whole string.

To make it short - take everything what’s befor the “dot” in the computername and replace the complete computername with it.

In this example you would have only “ComputerName” after the replacement.


Therefore it takes everythig before the first dot.
“$1” is what was confusing me most…

But why would computer name contain a dot?

The bit in brackets is a capture group. Capture groups are numbered from left to right, with $0 referencing the whole match, $1 referencing the capture group defined by the first set of brackets, and so on.

One thing that confused me with this is that you have to have the $n in single quotes. It doesn’t work on its own, and you don’t use it in double quotes like you would if you were expanding a variable.

'Hello World!' -replace '(Hello) (World)(!)', '$1 $0 $2 $3$3$3'

Probably working with a list of FQDNs and they just want the hostname.


That makes a lot sense! thanks.

I probably would have just done it like this:

$Computer = ($Computer -split '\.')[0]

I would prefer to write a function that checks if computer name is FQDN, NETBIOS name or UPN name, and then based on what it is perform appropriate spliting.

But before split I would also check for name syntax errors. :slightly_smiling_face: