Andy K
Andy K

Reputation: 5044

Running a script block for PowerShell

When running the part below through PowerShell prompt, it does what it is supposed to do - change anything that contains MYID to MyValue.

(Get-Content C:/tmp/test.txt) | ForEach-Object {$_ -replace "MYID", "MyValue"} | Set-Content C:/tmp/test.txt

Yet when I'm running it through a script block like below, it fails:

PowerShell Invoke-Command -ScriptBlock {Get-Content C:/tmp/test.txt | ForEach-Object {$_ -replace "MYID", "MyValue"} | Set-Content C:/tmp/test.txt}

Below is the trace of the command above

λ powershell invoke-command -scr {get-content c:\tmp\test.txt | foreach-object {$_ -replace "MYID", "MyValue"} | set-content c:\tmp\test.txt} 'foreach-object' n’est pas reconnu en tant que commande interne ou externe, un programme exécutable ou un fichier de commandes.

I tried to do diverses variations like the one below

 powershell invoke-command -scr {(get-content c:\tmp\test.txt) | (foreach-object {$_ -replace "MYID", "MyValue"}) | (set-content c:\tmp\test.txt)}

The command above, gives me the following error

} was not expected.

Any ideas?

Upvotes: 0

Views: 980

Answers (1)

Ben N
Ben N

Reputation: 2923

You don't need to use Invoke-Command or a script block if you just want to execute a command on the local machine under normal conditions. Rather, we can just use the -Command switch to PowerShell:

powershell -command "(get-content c:\tmp\test.txt) | foreach-object { $_ -replace 'MYID', 'MyValue' } | set-content c:\tmp\test.txt"

Note the single quotes around the -replace strings; this avoids problems with the command processor's escaping. This command works on my machine with a multiline file, but if it gives you trouble with the file still being open, you can use this version, which reads the file in full rather than line by line:

powershell -c "(get-content c:\tmp\test.txt -raw) -replace 'MYID', 'MyValue' | set-content c:\tmp\test.txt -nonewline"

Upvotes: 2

Related Questions