【问题标题】:Why is the PowerShell SetEnvironmentVariable command deleting the existing variable?为什么 PowerShell SetEnvironmentVariable 命令会删除现有变量?
【发布时间】: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


【解决方案1】:

改变这一行:

  Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable","$MyEnvVar","Machine")}

到:

 Invoke-Command $Computer -ScriptBlock {[System.Environment]::SetEnvironmentVariable("MyVariable",$Using:MyEnvVar,"Machine")}

来自about_scopes

示例 5:在远程命令中使用局部变量

对于在本地会话中创建的远程命令中的变量,请使用使用范围修饰符。 PowerShell 假定远程命令中的变量是在远程会话中创建的。

也结帐about_remote_variable

【讨论】:

  • 这就像一个魅力,我在这个过程中学到了一些新东西,谢谢。
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 2022-09-05
相关资源
最近更新 更多