![](/img/trans.png)
[英]Powershell: Exception calling “AttachDatabase” with “3” argument(s)
[英]Exception calling “Add” with “2” argument(s) when creating Powershell dictionary
我正在尝试从以下文件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
可能是什么原因导致的?如何解决?
“键不能为空。” - $_.type
计算结果不符合预期。 ( Get-Content
返回文本行,对CSV文件/列一无所知。)
该错误消息具有误导性,因为该问题与参数数量无关。 这只是PowerShell提供有关动态方法调用的一些详细信息。
在任何情况下,除非出现上述问题,否则为了保持一致,可以将Add
重写为$dict[$_.type] = @($_.hostname)
。 当然,首先需要正确读取CSV数据。
您可以尝试将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.