简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM