PowerShell: Active Directory Cleanup – Part 2 – Spacey Computer Names

Introduction

Hello again, Scott Williamson back with the next installment in the series “PowerShell: Active Directory Cleanup”. For this installment we going to take a look at a script that finds computers that have a space in their name. Per RFC 1123 DNS host names cannot contain white space (blank) in their names. This is the most common issue I’ve found when computers are entered manually by IT administrators. When typing we get so used to adding a space between words that we accidentally do it when creating computer names. Usually the space is at the end of the computer name so it’s not easily spotted. This script looks searches Active Directory for computers with a space in their name, writes them to a CSV file, and displays them to the screen for review.

Find Computers with Space(s) in the Name

# Clear the Screen
cls

# This section sets the common variables for the script.
# Get the current date and format it as yyyyMMdd.  The 4 digit year, 2 digit Month and 2 digit day.  Exmaple 20191213
$CDate = Get-Date -format "yyyyMMdd" 

# Get the location this script was executed from.
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent

# Set an array to the additonal Computer Properties we need.
$ComputerPropsCustom = $("Enabled","Description","LastLogonDate","Modified","whenChanged","PasswordLastSet","OperatingSystem","OperatingSystemServicePack","IPv4Address")

# Set an array to all the computer properties we want to display.
$ComputerPropsSelect = $("Name","SamAccountName","Enabled","DistinguishedName",@{Name="CreatedBy";Expression={$(([ADSI]"LDAP://$($_.DistinguishedName)").psbase.ObjectSecurity.Owner)}},"LastLogonDate","Modified","whenChanged","PasswordLastSet","OperatingSystem","OperatingSystemServicePack","IPv4Address")

# Search Active Directory for computer objects with a space in their name and sort them by Name.
$ComputerWithSpaces = Get-ADComputer -Filter {Name -like "* *"} -Properties $ComputerPropsCustom | Select-Object $ComputerPropsSelect | Sort-Object Name

# Export the results to a CSV file for review.
$ComputerWithSpaces | Export-Csv -Path "$ScriptPath\$($CDate)_ComputersWithSpaces.csv" -NoTypeInformation

# Display the results to the screen.
$ComputerWithSpaces

I included comment lines above each step to explain what the next line is doing. When writing PowerShell scripts it’s extremely helpful to add comments so that others viewing your scripts can understand what they are doing. These comments will also help you a year or two from now when you go back to use or modify the script.

Summary

Notice the similarities between the script above and the one from Part One. They both have very similar code with the exception of the filter and result variable names. Stay tuned for Part 3 of the series.

Leave a Reply