Search code examples
powershellreplacedirectoryservices

Powershell passing object as part of .replace


I have a script that I am writing to return all of the users and their OUs that have mailboxes. My only problems is that distinguishedname returns

CN=user,OU=...

I just want OU=...

It is my last line that is not formatted correctly

$($objItem.distinguishedname.replace('CN=$($objItem.name),',''))"

In this piece of the last line I want to replace where I find the phrase CN= data returned from the object with a blank.

So if $(objItem.name) contained Bob

I would want this to perform the following replace

$objItem.distinguishedname.replace('CN=Bob,','')

How would I format this? I have also tried the following

$($objItem.distinguishedname[0].replace('CN=$($objItem.name),',''))

which doesn't return an error but replaces nothing. If I change it to

$($objItem.distinguishedname[0].replace('CN=',''))

it removes all the CN= in front. I feel close.

Below is the full script.

$strFilter = "(&(&(&(objectCategory=Person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)(HomeMDB=*)))))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colProplist = "name","distinguishedname", "samaccountname"

foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)
{
    $objItem = $objResult.Properties; 
    write-Host "$($objItem.samaccountname) $($objItem.name)$($objItem.distinguishedname.replace('CN=$($objItem.name),',''))"
}

Solution

  • PowerShell doesn't expand variables inside of single quotes:

    'CN=$($objItem.name),'
    

    Perhaps you want this:

    "... $($objItem.distinguishedname[0].replace(`"CN=$($objItem.name),`",''))"
    

    Here's an example:

    $objItem = [pscustomobject]@{DistinguishedName='CN=Bob,OU=blah','';Name='Bob'}
    "Blah ... $($objItem.distinguishedname[0].replace(`"CN=$($objItem.name),`",''))"
    

    Outputs:

    Blah ... OU=blah