0

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?

1
  • Thanks Ansgar, there are multiple values in commented section like this: <#---------Use below sample to update config settings-------------------------------------- $Global:DeploymentType = 'S' $Global:VersionNumber = '18.1.0.1206.115' $Global:ServerIP = '10.130.60.55' ------------------------------------------------------------------------------------------#> Commented Dec 11, 2018 at 12:57

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.