Basic PowerShell Script Issue: “Expressions are only allowed as the first element of a pipeline”

后端 未结 2 1120
情深已故
情深已故 2021-01-17 21:11

I\'m trying to write a simple script that reads a file, locates a string, replaces the string with another string, and stores all new file contents (with replaced string), i

2条回答
  •  被撕碎了的回忆
    2021-01-17 22:04

    The problem is the second element in your pipeline.

    {$_ -replace "this:text", "withthis:text"}
    

    This is a scriptblock (i.e. a piece of code). If you want to apply a scriptblock to all of the incoming items on a pipeline you can use the foreach-object cmdlet like this:

    (Get-Content C:\file1.txt) | foreach-object {$_ -replace "this:text", "withthis:text"} | Set-Content C:\file2.txt
    

    @shagun is using the % alias for the foreach-object cmdlet, so that code looks correct as well.

提交回复
热议问题