Tuesday, March 4, 2014

OU to Environment Variable Script

So you want to know what OU your server is in to take some kind of action.  I like to load this data into an envrionment varibale so I can have it handy.  Here is my powershell solution:

$DS = New-Object System.DirectoryServices.DirectorySearcher
 $DS.Filter =  "(&(objectCategory=Computer)(Name=$env:computername))"
 $DN = ($DS.FindOne()).GetDirectoryEntry().DistinguishedName
 $ou=$DN[0].substring($DN[0].indexof(",OU=")+4)
 if ($ou.indexof(",OU="))  {$ou=$ou.substring(0,$ou.indexof(",OU="))}
 else  {$ou=$ou.substring(0,$ou.indexof(",DC="))}
[Environment]::SetEnvironmentVariable("OU",$OU,"Machine")

Enjoy.

No comments:

Post a Comment