2014-12-03 50 views
0

我試圖使用PowerShell搜索AD屬性otherTelephone,如果該值爲空,則在序列中添加下一個數字。例如,如果我添加一個名爲John的新用戶,我希望PowerShell檢查AD並查看最後使用的otherTelephone號碼是999,因此它會自動爲John添加1000。根據上一個值將增加的數字添加到AD屬性

到目前爲止,我已經成功地導出AD用戶的列表,其各自的otherTelephone號一起:

Get-ADUser -Filter * -Properties otherTelephone | 
    select name, @{L='otherTelephone'; E={$_.otherTelephone[0]}}, | 
    Export-Csv c:\aduser.csv -NoTypeInformation 

,但我不知道如何從那裏繼續。

+1

您可以先獲取所有數字,將它們管理爲排序對象,選擇最高值,然後將其設置爲1 – Paul 2014-12-03 17:37:18

回答

0

由於@Paul在你的問題的評論中提出:從AD讀取電話號碼,得到最高的號碼,並增加它。

$nextPhoneNumber = Get-ADUser -Filter * -Properties otherTelephone | 
        ? { $_.otherTelephone } | 
        select -Expand otherTelephone | 
        % { [int]$_ } | sort -Desc | select -First 1 
$nextPhoneNumber++ 

說明:

  • ? { $_.otherTelephone }:確保只有具有非空的屬性被處理的對象。
  • select -Expand otherTelephone:展開屬性,以便獲得一串電話號碼。這也涉及分配給用戶的多個號碼(該屬性是多值的)。
  • % { [int]$_ }:將每個電話號碼從一個字符串轉換爲一個整數,因此可以對它們進行數字排序。
  • sort -Desc:按降序對列表進行排序(第一個數字最高)。
  • select -First 1:從列表中選擇第一個數字並放棄其餘數字。
  • $nextPhoneNumber++:1。

增加數。如果您需要爲尚未填充otherTelephone屬性的所有現有用戶做到這一點,你可以做這樣的事情:

$users = Get-ADUser -Filter * -Properties otherTelephone 

$nextPhoneNumber = $users | ? { $_.otherTelephone } | 
        select -Expand otherTelephone | 
        % { [int]$_ } | sort -Desc | select -First 1 

$users | ? { -not $_.otherTelephone } | % { 
    $nextPhoneNumber++ 
    Set-ADUser -Identity $_.DistinguishedName -Replace @{ 
    'otherTelephone' = $nextPhoneNumber 
    } 
}