我正在尝试从以下文件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
可能导致它的原因以及如何解决它?
答案 0 :(得分:1)
“密钥不能为空。” - $_.type
未评估预期结果。 (Get-Content
返回文本行,但对CSV文件/列一无所知。)
错误消息具有误导性,因为问题与参数的数量无关;这只是PowerShell提供了有关动态方法调用的一些细节。
在任何情况下,除非上述问题,Add
可以重写为$dict[$_.type] = @($_.hostname)
以保持一致性。当然,需要首先正确读取CSV数据。
答案 1 :(得分: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