gpt4 book ai didi

powershell - 为什么我需要先把变量放到一个变量上

转载 作者:行者123 更新时间:2023-12-03 14:32:08 25 4
gpt4 key购买 nike

为了清理我的编码风格,我一直在玩弄乱七八糟的东西(知道不喜欢多少反引号)所以我们最终得到了这样的东西

$splat = @{
"ResourceGroupName" = $ResourceGroupName
"Location" = $location
"WhatIf" = $true
"ErrorVariable" = "err"
"ErrorAction" = "SilentlyContinue"
}
New-ResourceGroup @splat

我一直觉得不自然,我不喜欢参数出现在 cmdlet 之前。烦死我了!

所以我很好奇为什么这不能/不起作用。 (以及是否可以这样做)
New-ResourceGroup @{
"ResourceGroupName" = $ResourceGroupName
"Location" = $location
"WhatIf" = $true
"ErrorVariable" = "err"
"ErrorAction" = "SilentlyContinue"
}

这对我来说感觉更自然。有没有办法做到这一点?还是我永远注定要把车放在马之前......

编辑添加

如果没有答案,我已经发布了 Uservoice建议 - 随意去投票。

最佳答案

不幸的是,这是不可能的 AFAIK。问题是 @splat不是简单地传递哈希表(它是单个值)。不像 $它只是读取变量,splatting-operator @拆分单个对象(集合)并将其与参数匹配。此外,除了传递参数值之外,splatting-operator 不能用于其他任何事情。

PS C:\Users\frode> @splat
At line:1 char:1
+ @splat
+ ~~~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@splat' can be used only a
s an argument to a command. To reference variables in an expression use '$splat'

因此,我们不能在子表达式(例如 dir @(@{ Filter = "notepad.exe" }))或类似的东西中使用它来直接在 cmdlet 调用中创建哈希表。

我同意这会很棒,我建议在 PowerShell @ UserVoice 上提交功能请求.预先创建哈希表仍然需要付出很小的代价来获得更具可读性的脚本。

关于powershell - 为什么我需要先把变量放到一个变量上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188172/

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