PowerShell 散列-table return 值

PowerShell hash-table return values

我有一个简单的脚本 return 来自散列的值 table:

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

您正在终止字符串,然后使用 $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