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

后端 未结 2 1121
情深已故
情深已故 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 21:44

    I guess it is because after first pipe you are not processing each result. so the right one will be according to me :

    (Get-Content C:\file1.txt) | %{$_ -replace "this:text", "withthis:text"} | Set-Content C:\file2.txt
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题