0

I'm pulling the hostnames from all computers in an AD domain and the current command formats it in url form with the hostname at the end. I just need the hostnames so I'd like to strip everything to the left of the last forward slash.

(([adsi]"WinNT://$((Get-WMIObject Win32_ComputerSystem).Domain)").Children).Where({$_.schemaclassname -eq 'computer'}) | %{ $_.Path }

It's outputting as it should, I just happen to just need the hostname, so instead of WinNT://subdomain.somedomain.local/hostname I just got hostname which I would then redirect to an output file.

2 Answers 2

2

You can use the -Split operator to help retrieve the data:

"WinNT://subdomain.somedomain.local/hostname" -Split "/" | Select-Object -Last 1

-Split "/" separates the value into an array of substrings using / as a delimiter. You can access the resulting parts using array indexes or Select-Object. Since you want the last value, you could alternatively access [-1] index of the resulting array (("WinNT://subdomain.somedomain.local/hostname" -Split "/")[-1]).

See About Split for more information and examples.

Sign up to request clarification or add additional context in comments.

Comments

0

Just posting another option, and something else that may be useful. You can also split strings by their last index, which is the last time a character appears in it. From there you can use the Substring method to select the remainder of the string.

$lio = "WinNT://subdomain.somedomain.local/hostname".LastIndexOf('/')
"WinNT://subdomain.somedomain.local/hostname".Substring($lin + 1) # +1 to not include the slash

You can see all the methods for a string here

For things like this, I would also suggest looking at the ActiveDirectory module. You can run Get-ADComputer and select specific fields really easily.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.