Kushal Solanki
Kushal Solanki

Reputation: 127

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?

Upvotes: 0

Views: 590

Answers (3)

rahul
rahul

Reputation: 294

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

Upvotes: 0

montonero
montonero

Reputation: 1741

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

Upvotes: 2

Brank Victoria
Brank Victoria

Reputation: 1455

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'

Upvotes: 0

Related Questions