[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.
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.
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.