简体   繁体   中英

How to update global variable in another file in PowerShell?

I have created one PowerShell file called Config.ps1 which contains variables which are used by all other PowerShell scripts. As per below sample, it contains commented section (for user's understanding) and real variable which are updated at run time.

<#$Global:DeploymentType = 'Full/Partial'#>

$Global:DeploymentType = ''

I am calling that config ps file in another script file. Like below

$ConfigFile = Split-Path -Path $PSCommandPath
$ConfigFile = $ConfigFile + "\Config.ps1"
."$ConfigFile"

$Config = Get-Content $ConfigFile

Do some tasks: 1.2.3 then update variables based on those task

$Config = $Config -creplace "DeploymentType = '[^']*'","DeploymentType = 'Full'"
$Config | Set-Content $ConfigFile -Force

Issue is that, both commented part and variable in config file is getting updated. I just want to update variable value and not the commented part. Any way to achieve that?

Use this code instead:

$Config = $Config -creplace "DeploymentType = '[^']*'$","DeploymentType = 'Full'"

It will only replace the text that has an end of line after a last quote.

It depends on your config actually how to make a regexp. Probably some other restrictions should be specified

When you are taking your script as content you don't know which is a part of comment and which is not. So you have to replace the first parameter of the method -creplace to a more specific regular expression. For example:

$Config = $Config -creplace "DeploymentType = \'(Full|Partial){0,1}\'","DeploymentType = 'Full'"

This means that this will replace the following text:

  • DeploymentType=''
  • DeploymentType='Full'
  • DeploymentType='Partial'

The comment will not be replaced because the value is

DeploymentType='Full/Partial'

u can write a regular expression and compare lines on it like \\$Global:. =\\s ('')

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.

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