Jay Parken
Jay Parken

Reputation: 213

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

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), in a new file. Here is what I'm using:

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

The error I'm receiving is: "Expressions are only allowed as the first element of a pipeline"

I'm pretty sure this is because of the colon ":" character being in both the string I'm locating and replacing it with. I've tried escaping the colon character with "\" and "`" characters, but I'm receiving the same errors. Does anyone know what's wrong with this?

Thanks for the help.

Upvotes: 21

Views: 45366

Answers (2)

Mike Shepard
Mike Shepard

Reputation: 18166

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.

Upvotes: 28

Shagun Sharma Tamta
Shagun Sharma Tamta

Reputation: 71

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

Upvotes: 4

Related Questions