Hi,
I’m looking to split an AD path into it’s component parts, remove the domain and machine name and re-order the OU into a left to right format. For example, if I have the AD path ‘CN=SPARE-LAPTOP,OU=Laptops,OU=Workstations,DC=domain,DC=local’ I want the output to be ‘Workstations>Laptops’.
I am currently working on spitting the string into it’s component parts and putting it into an array and have:
$OU = @{ (("CN=SPARE-LAPTOP,OU=Laptops,OU=Workstations,DC=domain,DC=local").TrimEnd(",DC=domain,DC=local") -split ",").substring(3) }
When I run this I get:
[blockquote]At line:1 char:138
Missing ‘=’ operator after key in hash literal.
At line:1 char:138
The hash literal was incomplete.
+ CategoryInfo : ParserError: ( , ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral[/blockquote]
Any advice on what I’m doing wrong?
As you’re initiating a hashtable you have to give the value a name, for example:
$OU = @{
VariableName = (("CN=SPARE-LAPTOP,OU=Laptops,OU=Workstations,DC=domain,DC=local").TrimEnd(",DC=domain,DC=local") -split ",").substring(3)
}
PS C:\Users\mni> $OU
Name Value
VariableName {SPARE-LAPTOP, Laptops, Workstations}
PS C:\Users\mni> $OU.VariableName
SPARE-LAPTOP
Laptops
Workstations
Let’s take it step by step :
$OU = (("CN=SPARE-LAPTOP,OU=Laptops,OU=Workstations,DC=domain,DC=local").TrimEnd(",DC=domain,DC=local") -split ",")
This gives the following array of strings :
[blockquote] CN=SPARE-LAPTOP
OU=Laptops
OU=Workstations [/blockquote]
Now, let’s filter the items starting with “OU=” and get rid of the “OU=” in these items :
$OUMatches = $ou | Select-String -Pattern "^OU=" | ForEach-Object { $_ -replace "OU=", "" }
Then, reverse the order in the array :
$Reversed = $OUMatches[-1], $OUMatches[0]
This gives us the following value for $Reversed :
[blockquote] Workstations
Laptops [/blockquote]
Now, we just need to transform our array back to a string :
$Reversed -join '>'
This ouputs the following :
[blockquote] Workstations>Laptops [/blockquote]