0

我正在尝试从以下文件 hostname.csv 创建字典:

hostname        type
LON131          gaming
LON132          gaming
LON133          research
LON134          research

使用以下 Powershell 脚本:

get-content hostname.csv | ForEach-Object {
    if ($dict.Keys -contains $_.type) {
        $dict[$_.type]+=$_.hostname
    } else {
        $dict.Add($_.type,@($_.hostname))
    }
}

Write-Host $dict;

但我不断收到以下错误消息:

Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At fcheck.ps1:7 char:29
+         $dict.Add($_.type,@($_.hostname))
+                             ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At fcheck.ps1:7 char:29
+         $dict.Add($_.type,@($_.hostname))
+                             ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At fcheck.ps1:7 char:29
+         $dict.Add($_.type,@($_.hostname))
+                             ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At fcheck.ps1:7 char:29
+         $dict.Add($_.type,@($_.hostname))
+                             ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At fcheck.ps1:7 char:29
+         $dict.Add($_.type,@($_.hostname))
+                             ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

可能是什么原因造成的,我该如何解决?

4

2 回答 2

1

您可以尝试替换get-content hostname.csv为:

Import-CSV -Delimiter "`t" -Path hostname.csv

编辑:

我认为您可能没有在dict调用 priro 之前进行初始化$dict.keys。以下对我有用:

$dict = @{} 
Import-Csv -Path .\test.csv -Delimiter "`t" | ForEach-Object {
    if ($dict.Keys -contains $_.type) {
        $dict[$_.type]+=$_.hostname
    } else {
        $dict[$_.type] = @($_.hostname)
    }
}

$dict
于 2013-09-30T22:18:32.483 回答
1

“密钥不能为空。” -$_.type没有评估到预期的结果。(Get-Content返回文本行并且对 CSV 文件/列一无所知。)

该错误消息具有误导性,因为该问题与参数的数量无关;这只是 PowerShell 提供了有关动态方法调用的一些详细信息。

在任何情况下,除非出现上述问题,Add否则可以将其重写$dict[$_.type] = @($_.hostname)为统一性。当然,首先需要正确读取 CSV 数据。

于 2013-09-30T22:12:34.607 回答