[英]Powershell Set-Variable resets Variable instead of updating it
I'm confused on how to use Set-Variable
to change a specific value in a variable.我对如何使用
Set-Variable
更改Set-Variable
中的特定值感到困惑。 I don't understand the resulting behavior.我不明白由此产生的行为。 I am trying this in Powershell 5.1.
我正在 Powershell 5.1 中尝试这个。
If I create a new variable with New-Variable
如果我用
New-Variable
创建一个新New-Variable
New-Variable -Name TestVariable -Value @{Name1 = 'Value1'; Name2 = 'Value2'}
And then I try to change it with Set-Variable
然后我尝试用
Set-Variable
改变它
Set-Variable -Name TestVariable -Value @{Name1 = 'NewValue'}
Why is my output now:为什么我的输出现在是:
Name Value
---- -----
Name1 NewValue
and not as expected:而不是预期的:
Name Value
---- -----
Name1 NewValue
Name2 Value2
Set-Variable
appears to reset the whole variable instead of changing it. Set-Variable
似乎重置整个变量而不是更改它。 Or creating a new variable without the -Force
setting, which is kind of scary.或者创建一个没有
-Force
设置的新变量,这有点可怕。
The description from the Microsoft docs say: Microsoft 文档中的描述说:
The Set-Variable cmdlet assigns a value to a specified variable or changes the current value.
Set-Variable cmdlet 将值分配给指定的变量或更改当前值。 If the variable does not exist, the cmdlet creates it.
如果变量不存在,cmdlet 会创建它。
Do I misunderstand the or changes part somehow?我是否以某种方式误解了或更改了部分?
I've also tried to store the parameters in a variable itself instead of writing it out after the -Value
however that results in the same behavior as expected.我还尝试将参数存储在变量本身中,而不是在
-Value
之后将其写出,但这会导致与预期相同的行为。
Now if I do change the value without Set-Variable
it works just fine.现在,如果我在没有
Set-Variable
情况下更改值,它就可以正常工作。
$TestNewVariable.Name1 = 'NewValue'
and the output is exactly as expected:并且输出完全符合预期:
Name Value
---- -----
Name1 NewValue
Name2 Value2
The Solution would be instead of changing a value in the variable is to just write all values again.解决方案不是更改变量中的值,而是再次写入所有值。 However I'd be very interested to know why the
Set-Variable
is not just changing the value or what I am doing wrong.但是,我很想知道为什么
Set-Variable
不只是改变值或我做错了什么。
不像名称Set-Variable
可能暗示它用于编辑变量值,它仅用于编辑变量属性,例如 -Scope、-Visibility、-Description 等。其中可以是变量的 -Value,但只能将 Value 作为整体而不是值属性,因为Set-Variable
在任何时候都不关心值属性,因此无法编辑它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.