Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

scripting - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...