Recently I had written a script that disables inactive workstations and moves them to a “Disabled Computers” OU. The key to this is that the script writes the original OU DN in the computer’s description field so it can be moved back if needed. The only problem is I enclosed the OU DN in parentheses “(“ “)” which is a special character in Powershell. When I was adding the component that would move these computers back to their original location, I had to escape out the parentheses by using “\(” “\)” – typically the escape character in Powershell is “`”.
This is what I ended up doing:
import-module activedirectory
$RepChr1 = “\)” # Escape the ( and set as variable
$RepChr2 = “\(” # Escape the ) and set as variable
$ComputerInfo = Get-ADComputer $Computer -property * # Get the AD information for the computer
$ComputerInfoName = $ComputerInfo.Name # Get the computer name and set to variable (Yeah, I know I already have it, but I do this for consistency
$ComputerInfoDescription = $ComputerInfo.Description # Get the computer description
$ComputerInfoDescription = $ComputerInfoDescription -replace (“$RepChr1″,”#”) # Replace the ( with a # for splitting
$ComputerInfoDescription = $ComputerInfoDescription -replace (“$RepChr2″,”#”)# Replace the ) with a # for splitting
$ComputerInfoDNExtracted = $ComputerInfoDescription -split (“#”) # Split on the # in order to separate the OU DN
$MoveComputerTargetOU = $ComputerInfoDNExtracted[1] # Set the OU DN the computer will move back to
$MoveComputerTargetOU = $MoveComputerTargetOU =-replace (“CN=$ComputerInfoName,”,”") # Remove the Computername element from the OU DN
With this, I can now move the computer back to its original location.
Move-ADObject -Identity “$ComputerInfoDistinguishedName” -TargetPath “$MoveComputerTargetOU”
Obviously, this is part of a ForEach Loop with the list of computers that were modified.