函数中的 Powershell 哈希表不可访问

Powershell hashtable in function not accessible

我创建了一个函数来导入 HR 记录,以便通过索引 employeeID 轻松访问它们。

function hrDataImport {
$HRFile=Import-Csv $rawHRFile #$rawHRFile path previously defined
Write-Host "Creating HR hash table..."
$hrData = @{}
$HRFile | ForEach-Object { $hrData[$_.employeeID] = $_ }
Write-Host "Done. " $hrData.Count
    }

我想在函数外使用 $hrData 变量。我无法引用 $hrData['employeeID'] 因为我读过函数中的变量在函数外不存在。我尝试的一件事是创建另一个函数以将 employeeID 传递到 $hrData 哈希表中:

function showHRData {
    param ([string]$hrUser)
    $hrData[$hrUser]
}

我把函数放在一个模块中并成功导入。我能够很好地执行 importHRData 但是当我尝试 showHRData -hrUser $employeeID 时,我得到“无法索引到空数组”。似乎该函数没有看到前一个函数的哈希表变量。我做错了什么或者您有什么建议以便我可以跨各种脚本访问 $hrData 哈希表?

您可以使用 $global(或 $scriptscope 在函数中创建哈希表,如下所示:

function hrDataImport {
    $HRFile = Import-Csv $rawHRFile #$rawHRFile path previously defined
    Write-Host "Creating HR hash table..."
    if (!$hrData) { $Global:hrData = @{} }
    $HRFile | ForEach-Object { $Global:hrData[$_.employeeID] = $_ }
    Write-Host "Done. " $hrData.Count
}

但通常建议避免使用全局(或脚本)作用域,主要是因为它可能与当前作用域中的变量发生冲突。
为了尽量减少这种可能性,我会考虑将您的功能的职责更改为不仅加载信息而且接收相关的信息 employeeID,例如:

function Get-EmployeeData ($EmployeeID) {
    if (!$StaticEmployeeData) {
        Write-Host "Creating HR hash table..."
        $HRFile = Import-Csv $rawHRFile #$rawHRFile path previously defined
        $Global:StaticEmployeeData = @{}
        $HRFile | ForEach-Object { $Global:StaticEmployeeData[$_.employeeID] = $_ }
        Write-Host "Done. " $StaticEmployeeData.Count
    }
    $Global:StaticEmployeeData[$employeeID]
}

function showHRData {
    param ([string]$hrUser)
    Get-EmployeeData $hrUser
}

在这种情况下,您可以选择更具体的全局变量名称(例如 $StaticEmployeeData,知道 PowerShell 不支持类似 static variable) and as an extra bonus the data is only loaded the first time you really need it (lazy evaluation 的名称)。