【发布时间】:2019-05-15 14:42:33
【问题描述】:
大家好,
我编写了一个 PowerShell 函数来帮助我在一堆 Windows 7 和 10 Enterprise 计算机上更新系统环境变量。但是,我注意到我的 "[System.Environment]::SetEnvironmentVariable()" 命令正在删除现有变量而不是更改其值 - 就像我期望的那样。 p>
我做错了什么?
这是相关代码的sn-p:
$ComputerName = "SERVER1"
$MyEnvVar = "C:\Some_Path\"
ForEach ($Computer in $ComputerName){
$Online = Test-Connection -ComputerName $Computer -Count 2 -Quiet
If ($Online -eq $True){
$OldValue = Invoke-Command $Computer -ScriptBlock {[System.Environment]::GetEnvironmentVariable("MyVariableName","Machine")}
Write-Host "Old Value is: $OldValue"
Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable","$MyEnvVar","Machine")}
$NewValue = Invoke-Command $Computer -ScriptBlock {[System.Environment]::GetEnvironmentVariable("MyVariableName","Machine")}
Write-Host "New Value is: $NewValue"
}
}
【问题讨论】:
-
$MyEnvVar是在远程机器的上下文中评估的,而不是您的本地值。使用$using:MyEnvVar远程控制它。 -
当我声明 $MyEnvVar 或在 Set 命令中使用它时,我会这样做吗?
标签: windows powershell