0

Hi I am trying to change the content of a file through Powershell but its not working:

$mf_runw_user = 'abc'
$mf_runw_pass = facter -p mf_runw_pass
$run_path = "D:\MF_Dashboard\NMFD\Runway\Web.config"
(Get-Content "$run_path").replace('"USERID" value="*"', '"USERID" value="$mf_runw_user"') | Set-Content "$run_path"
(Get-Content "$run_path").replace('"PASSWORD" value="*"', '"PASSWORD" value="$mf_runw_user"') | Set-Content "$run_path"

Basically I need the below output:

<add key="USERID" value="abc" />
<add key="PASSWORD" value="123qweasd" />

but i am getting this output:

<add key="USERID" value="$mf_runw_user" />
<add key="PASSWORD" value="$mf_runw_pass" />

Please Help me on this.

1 Answer 1

1

Because it's wrapped in single quotes the variable isn't expanding:

Try something like:

(Get-Content $run_path).Replace('"USERID" value="*"', "`"USERID`" value=`"$mf_runw_user`"") | Set-Content $run_path
(Get-Content $run_path).Replace('"PASSWORD" value="*"', "`"PASSWORD`" value=`"$mf_runw_user`"") | Set-Content $run_path

This is just escaping the double quotes where necessary.

Using the formatting operator may also work:

(Get-Content $run_path).Replace('"USERID" value="*"', '"USERID" value="{0}"' -f $mf_runw_user) | Set-Content $run_path
(Get-Content $run_path).Replace('"PASSWORD" value="*"', '"PASSWORD" value="${0}"' -f $mf_runw_user) | Set-Content $run_path

Note

You have $mf_runw_user in both replace expressions. I think you probably want an expression for the password in the second one.

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

1 Comment

The First I tried with escape sequence and it worked. Thanks @steven

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.