0

Using powershell, I want to take a .bat file and replace all lines in which set is called to set an environment variable and change it to a corresponding setx call. Unfortunately it's not as simple as just doing a search and replace on the file, replacing set for setx, because the syntax is diffferent: set ENVNAME=abc vs setx ENVNAME abc.

Is there a simple way to do this in powershell? To just do the set for setx replacement, I have:

(Get-Content $orig_filename ) | ForEach-Object {$_ -replace "set", "setx"} | Set-Content $new_filename

Any pointers for a powershell novice would be appreciated.

2 Answers 2

2

Did some pretty limited testing and I'm not sure what your bat file looks like, but this may work for you.

(Get-Content $orig_filename ) | ForEach-Object {
    $_ -replace 'set (.*)\=(.*)','setx $1 $2'
} | Set-Content $new_filename
Sign up to request clarification or add additional context in comments.

Comments

1

You could also just chain another -replace to do the work for you. Also made the set > setx replacement a little more less error prone by ensuring you are replacing the word set at the beginning of the string. Since -replace functions as an array operator you do not need the foreach loop.

(Get-Content $orig_filename ) -replace "^set\b", "setx" -replace "="," " | Set-Content $new_filename

1 Comment

Thanks for your suggestion. Realizing what I want to do is a bit more complicated because I also need to account for translating set ABC= (to unset) to setx ABC "". Thinking maybe a different strategy might be easier, but still need to figure it out: stackoverflow.com/questions/32406439/…

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.