csv 将数据匹配到哈希表(PowerShell)

bpsygsoo  于 2023-06-19  发布在  Shell
关注(0)|答案(1)|浏览(143)

我有个问题
我已经创建了2个哈希表- $Office和$Departments,并从.csv导入。$Departments有标题OfficialDepartment和DepartmentGlCode。我想在此哈希表中搜索关键字'ICT Dept'并返回值。此作品独立x1c 0d1x
但是,如果我将其添加到脚本中,我的GetEnumerator(缺少“=”)会出现问题,我将代码发布到断点。您可能会问Get-ADUser部分是做什么用的,一旦我让这个部分工作了,我将从AD中查找$_.Department来匹配哈希表

$StartTime = Get-Date
$Offices = @{}
$Offices = Import-Csv -Path "D:\temp\OfficeGlCodes.csv" -Delimiter ","
$Departments = @{}
$Departments = Import-Csv -Path "D:\temp\DepartmentGlCodes.csv" -Delimiter ","
$Results = Get-ADUser -Filter {enabled -eq $true -and Description -eq "Staff" -and Office -eq "Head Office"} -Properties POBox, Office, Department | ForEach-Object {
    $Result = [PSCustomObject]@{
        Department      =   $_.Department
        Office          =   $_.Office
        OriginalGLCode  =   $_.POBox
        Date            =   $StartTime.ToString("d")
        $Departments.GetEnumerator() |ForEach-Object {
            if ($_.OfficialDepartment -eq 'ICT Dept') {
                Write-Output $_.DepartmentGlCode
            }
        }

输出:

ParserError: \\opvx341\homeshares$\Mike.Davidson\24. GL Code Project\initial.ps1:15:37

线|十五|$Departments.GetEnumerator()|ForEach-Object {|~~|哈希文本中的键后缺少“=”运算符。

kupeojn6

kupeojn61#

您当前正在创建空的哈希表,然后立即用Import-Csv的输出覆盖它们-所以现在您不再有哈希表了。
请改为执行以下操作:

$StartTime = Get-Date

# create empty hashtable
$Offices = @{}
# populate hashtable with data from CSV
Import-Csv -Path "D:\temp\OfficeGlCodes.csv" -Delimiter "," |ForEach-Object {
  $Offices[$_.OfficialOffice] = $_
}

# create empty hashtable
$Departments = @{}
# populate hashtable with data from CSV
Import-Csv -Path "D:\temp\DepartmentGlCodes.csv" -Delimiter "," |ForEach-Object {
  $Departments[$_.OfficialDepartment] = $_
}

$Results = Get-ADUser -Filter {enabled -eq $true -and Description -eq "Staff" -and Office -eq "Head Office"} -Properties POBox, Office, Department | ForEach-Object {
    # create an ordered hashtable to temporarily hold the output object's properties
    $properties = [ordered]@{
        Department       =   $_.Department
        Office           =   $_.Office
        OriginalGLCode   =   $_.POBox
        Date             =   $StartTime.ToString("d")
    }
    # now use hash tables to look up department/office codes and conditionally add property values
    $properties['DepartmentGlCode'] = if ($Departments.Contains($_.Department)){
        $Departments[$_.Department].DepartmentGlCode
    } 
    else {
        $Offices[$_.Office].OfficeGlCode
        # log discrenpancy here
    }

    # create and output final object
    [PSCustomObject]$properties
}

相关问题