String manipulation - Powershell

I have a file called notification.txt that has data in it that I need to trim and pass the trimmed output to another command.

File is a random number of lines, could be 1, could be 100+, they look like this:

hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification
hostname.domain.xyz                      Notification

I'm looking to trim everything from the first . to the right and it will just leave me with the hostname in a array/variable that I can then use to pass to another command.


You can remove everything after the first occurrence of . by calling Split and discarding everything except for the first part:

$strings = @(
  'host1.domain.tld       Notification'
  'host2.domain.tld       Notification'
  'host3.domain.tld       Notification'
  'host4.domain.tld       Notification'
  'host5.domain.tld       Notification'
)

$hostnames = $strings |ForEach-Object { $_.Split('.')[0] }

$_.Split('.') returns a string array (eg. @('host1','domain','tld Notification')), and [0] gives us the first element in said array


Alternatively, use the -replace regex operator:

$hostnames = $strings -replace '\..*$'

The regex pattern \..*$ will match the first literal dot . and everything after it until the end of the string, and since we're using the -replace operator with no substitute string as the second argument, that entire part gets removed.