简体   繁体   English

Powershell 为局部变量设置环境变量

[英]Powershell Setting Environment variable for local variable

I am getting a list of values from the command line in format of key=val key=val, after splitting them down and then into key and value, I want to set an environment variable using the key.我从命令行以 key=val key=val 的格式获取值列表,在将它们拆分然后分解为键和值之后,我想使用键设置一个环境变量。

I have tried the following code ($sstr is being set from arguments, but I have hard coded it to simplify the code), but I am getting 'unexpected token' error:我已经尝试了以下代码($sstr 是从 arguments 设置的,但我已经对其进行了硬编码以简化代码),但我收到了“意外令牌”错误:

$retrievedVal = "key1=val1 key2=val2"

# Split the string, with space being the delimiter, leaving key=value
$sstr = $retrievedVal .split( " " )

foreach ( $var in $sstr )
{
    $keyvalueList = $var.split( "=" )
    $env:($keyvalueList[0]) = "Test"
}

Any suggestions to where I have gone wrong would be greatly appreciated:)任何关于我哪里出错的建议将不胜感激:)

You can use Set-Item cmdlet: 您可以使用Set-Item cmdlet:

$Name,$Value='key1=val1'-split'=',2
Set-Item -LiteralPath Env:$Name -Value $Value

Also you could use [Environment]::SetEnvironmentVariable method: 你也可以使用[Environment]::SetEnvironmentVariable方法:

[Environment]::SetEnvironmentVariable($Name,$Value)

Note, what that only set process environment variables. 注意,那只能设置进程环境变量。 So, it affects only your process and child processes, started from that point. 因此,它仅影响您的流程和子流程,从那时开始。

You can also use the Set-Variable command in PowerShell:您还可以在 PowerShell 中使用Set-Variable命令:

Set-Variable -Name "..." -Value "..."

Then you can use a couple of commands to check that the variable was set properly: echo , Write-Host , Get-Variable :然后您可以使用几个命令来检查变量是否设置正确: echoWrite-HostGet-Variable

  1. echo $...
  2. Write-Host "$..."
  3. Get-Variable -Name "..."

Example 1:示例 1:

Set-Variable -Name "Employee" -Value "John"

echo $Employee 

Example 2:示例 2:

Set-Variable -Name "Employee" -Value "John"

Write-Host "$Employee" 

Example 3:示例 3:

Set-Variable -Name "Employee" -Value "John" 

Get-Variable -Name "Employee"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM