PowerShell:在表达式或语句中查询AD属性"意外标记

时间:2016-02-08 14:59:19

标签: string powershell active-directory

我最近不得不更改我的powershell脚本,以查询AD中不同属性的SIP地址。但是我不确定如何编写它以便我可以查询" msRTCSIP-PrimaryUserAddress"在Active Directory中。这是由于' - '在msRTCSIP-PrimaryUserAddress属性中。当我将鼠标悬停在波浪线上时,它会在表达式或语句中显示“#34;意外的令牌”#34;

我可以从AD中查询其他信息,例如姓名,mailnickname等。但我特别需要这个,因为我们改变SIP地址的方式。

Function CheckSIP {

    $loggedOnUser = (get-WmiObject win32_process -Filter "Name='explorer.exe'"|Select -First 1).GetOwner().User

    $strFilter = "(&(objectCategory=User)(mailnickname=$loggedOnUser))"
    $objDomain = New-Object 

    System.DirectoryServices.DirectoryEntry("LDAP://OU=Offices,dc=OurNetwork,dc=net")
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"

    $colProplist = "name", "mail", "mailnickname", "msRTCSIP-PrimaryUserAddress"
    foreach ($i in $colPropList){$null = $objSearcher.PropertiesToLoad.Add($i)}

    $colResults = $objSearcher.FindAll()

    foreach ($objResult in $colResults){

        $objItem = $objResult.Properties
        [string]$UserName = $objItem.name 
        [string]$mail = $objItem.mail
        [string]$mailnickname = $objItem.mailnickname
        [string]$sipaddress = $objItem.msRTCSIP-PrimaryUserAddress
    }

    $theSIP = $sipaddress.Split("@")[0]    
    return $theSIP
}

$mySIPaddress = CheckSip

我知道" Get-ADUser"命令,但不是我们所有的机器都会在他们的机器上本地拥有这个命令行开关。所以这就是我这样做的原因。

2 个答案:

答案 0 :(得分:1)

请记住,连字符是一个运算符。尝试:

[string]$sipaddress = $objItem.'msRTCSIP-PrimaryUserAddress'

您还需要为搜索者指定属性:

$colProplist = "name", "mail", "mailnickname","msRTCSIP-PrimaryUserAddress";
$objSearcher.PropertiesToLoad.AddRange($colProplist);

我也消除了不必要的循环。

答案 1 :(得分:0)

通过BaconBits建议并摆脱循环。这是工作函数的样子。

Function CheckSIP {
$loggedOnUser = (get-WmiObject win32_process -Filter "Name='explorer.exe'"|Select -First 1).GetOwner().User
$strFilter = "(&(objectCategory=User)(mailnickname=$loggedOnUser))"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Offices,dc=ourdomain,dc=net")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$colProplist = "name", "mail", "mailnickname", "msrtcsip-primaryuseraddress";
$objSearcher.PropertiesToLoad.AddRange($colProplist);

    $colResults = $objSearcher.FindAll()
    $objItem = $colResults.Properties
    [string]$sipaddress = $objItem.'msrtcsip-primaryuseraddress'
    $theSIP = $sipaddress.Split("@")[0]
    $theSIP2 = $theSIP.Split(":")[-1] 
    return $theSIP2
    }

正如您所看到的,我将其更改为msrtcsip-primaryuseraddress的所有小写,并且它有效。

谢谢BaconBits!