I'm confused on how to use Set-Variable
to change a specific value in a variable. I don't understand the resulting behavior. I am trying this in Powershell 5.1.
If I create a new variable with New-Variable
New-Variable -Name TestVariable -Value @{Name1 = 'Value1'; Name2 = 'Value2'}
And then I try to change it with 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. Or creating a new variable without the -Force
setting, which is kind of scary.
The description from the Microsoft docs say:
The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.
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.
Now if I do change the value without Set-Variable
it works just fine.
$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
可能暗示它用于编辑变量值,它仅用于编辑变量属性,例如 -Scope、-Visibility、-Description 等。其中可以是变量的 -Value,但只能将 Value 作为整体而不是值属性,因为Set-Variable
在任何时候都不关心值属性,因此无法编辑它们。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.