Running a powershell command inside cmd script and replacing string content

1.1k views Asked by At

I am trying to run a powershell command inside cmd script for replacing a text file content

set file="C:\myfile.txt"

powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace "Latest", "FOO" } | Set-Content %file%"

I am getting the following error:

You must provide a value expression on the right-hand side of the '-replace' operator.

What am I doing wrong?

Thanks

EDIT (not sure if relevant to the answer...)

The file content is

\\10.10.10.10\Shared\Latest
1

There are 1 answers

1
TessellatingHeckler On

You are not nesting strings correctly

powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace "Latest", "FOO" } | Set-Content %file%"
                    ^----------------------------------------------------^
               string start                                        string end

Use single quotes:

powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace 'Latest', 'FOO' } | Set-Content %file%"