gpt4 book ai didi

function - PowerShell哈希表返回值

转载 作者:行者123 更新时间:2023-12-03 01:14:50 24 4
gpt4 key购买 nike

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

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

关于function - PowerShell哈希表返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com