如何在Powershell中添加到此收藏集?

时间:2019-07-18 20:50:17

标签: powershell api

我正在从ITSM解决方案的REST API中提取一些数据,它从json中解析出来并放入一个名为$ listOfCurrentUsers的对象中。然后,我根据从Active Directory中提取的数据创建对象。然后,它检查AD用户是否存在于$ listOfCurrentUsers中,如果存在,它将记录ID添加到$ CAServiceDesk对象中。如果该用户不存在,它仍会添加记录ID,但会为其赋予空值。

$listOfCurrentUsers = Invoke-RestMethod -Method Get -Uri $getList -Header $requestHeader

Import-Module ActiveDirectory

$CAServiceDesk = Get-ADGroupMember "ServiceDesk" -Recursive |
ForEach-Object(
{
    Get-ADUser($_.samaccountname) -Properties * | 
        Select-Object -Property Name,
            @{Name = 'SAM Account Name'; Expression = {$_.samaccountname}},
            Department,
            @{Name = 'Telephone Number'; Expression = {$_.telephonenumber}},
            @{Name = 'Manager'; Expression = {($_.manager -split ',*..=')[1]}},
            @{Name = 'User Account Control'; Expression = {$_.useraccountcontrol}},
            Mail,
            @{Name = 'Employee ID'; Expression = {$_.employeeID}}

    if($listOfCurrentUsers.users | where { $_.PublicID -eq $CAServiceDesk.Name }) {
        Add-Member -InputObject  -MemberType NoteProperty -Name RecID -Value $_.RecordID}   
    else {
        Add-Member -InputObject  -MemberType NoteProperty -Name RecID -Value {"null"}}

}
) 

我被困在“如果是,那么这”部分。我似乎无法弄清楚如何将RecordID值分配给Add-Member?

1 个答案:

答案 0 :(得分:0)

您的代码似乎无效。您可能缺少第一个ForEach-Object的右括号,或者在表达式内使用了$CAServiceDesk,该表达式为$CAServiceDesk分配了一个值(即,调用时它将是一个空变量它)。

但是,如果我最好地猜测您在做什么以及对象的外观,我会这样写:

# This should give you a hash table that maps PublicID to RecordID.
# This will not work as I expect if PublicID can be duplicated.
$TableOfCurrentUsers = Invoke-RestMethod -Method Get -Uri $getList -Header $requestHeader |
    Select-Object -ExpandProperty users |
    Select-Object -Property PublicID, RecordID |
    Group-Object -Property PublicID -AsHashTable

# This will get the users and build your custom object
$CAServiceDesk = Get-ADGroupMember "ServiceDesk" -Recursive |
    Get-ADUser -Properties Name, SamAccountName, Department, TelephoneNumber, Manager, UserAccountControl, Mail, EmployeeID |
    Select-Object -Property Name,
        @{n = 'SAM Account Name'; e = {$_.samaccountname}},
        Department,
        @{n = 'Telephone Number'; e = {$_.telephonenumber}},
        @{n = 'Manager'; e = {($_.manager -split ',*..=')[1]}},
        @{n = 'User Account Control'; e = {$_.useraccountcontrol}},
        Mail,
        @{n = 'Employee ID'; e = {$_.employeeID}},
        @{n = 'RecID'; e = { $TableOfCurrentUsers[$_.Name] }}

请注意,除非确实需要,否则永远不要指定Get-ADUser -Properties *。其中一些属性很长,这会使您的LDAP查询花费相当长的时间。