Powershell哈希表返回值

时间:2015-08-25 17:29:19

标签: function powershell hashtable return-value

我有一个简单的脚本来从哈希表中返回值:

param 
(

    [Parameter(Mandatory = $true)]
    [string]$Name

)

function getvalues ($Name) {

$nameList= @{"CFT"=@{"name1"="text1"; "name2"="text2"}}

#return $nameList[$Name]
return ,$nameList
}

$Values    = getvalues($Name)

    write-Debug "DEBUG: Name1   = "$Values["name1"]
    write-Debug "DEBUG: Name2   = "$Values["name2"]

当我运行它时,我收到以下错误:

Write-Debug : A positional parameter cannot be found that accepts argument '$null'.
At C:\MSFT\add-test.ps1:21 char:2
+     write-Debug "DEBUG: Name1     = "$Values["name1"]
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Write-Debug], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteDebugCommand

Write-Debug : A positional parameter cannot be found that accepts argument '$null'.
At C:\MSFT\add-test.ps1:22 char:2
+     write-Debug "DEBUG: Name2     = "$Values["name2"]
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Write-Debug], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteDebugCommand

1 个答案:

答案 0 :(得分:3)

您正在终止字符串,然后使用$Values查找。使用+或将其嵌入字符串中,或​​使用-f运算符:

write-Debug ("DEBUG: Name1   = " + $Values["name1"])
write-Debug "DEBUG: Name2   = $($Values["name2"])"
write-Debug ("DEBUG: Name3   = {0}" -f $Values["name3"])

注意表单1和3需要括号( )

关于您的评论,没有更多错误,也没有输出:

您确定您的调试首选项已设置为可以查看输出吗? Write-DebugWrite-Verbose的要点是,您只能在首选项设置时看到输出(并且您不应在字符串中添加DEBUG:,它将为您添加)。我怀疑Write-Verbose更适合你正在做的事情。

要快速测试它是否有效,您可以根据需要实际添加-Debug-Verbose

例如:

Write-Verbose "Name2   = $($Values["name2"])" -Verbose
相关问题