drouning
drouning

Reputation: 385

How pipe after replace in PowerShell?

I would like a to replace characters inside a string and then split it. Example below:

$in = "string with spaces"
$out = $in -replace 's' | $_.Split(' ')

Leads to ExpressionsMustBeFirstInPipeline.

How come this doesn't work?

Upvotes: 2

Views: 1213

Answers (3)

G42
G42

Reputation: 10019

You can use the Replace string method instead. E.g to replace s with blank, and then split on space:

$out = $in.Replace('s','').split(' ')

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200313

There's nothing wrong with the result of the replacement going into the pipeline, but your next step doesn't actually read from the pipeline. For the construct you chose you need a ForEach-Object loop:

$out = $in -replace 's' | ForEach-Object { $_.Split(' ') }

or call Split() on the result of the replacement (without pipeline):

$out = ($in -replace 's').Split(' ')

However, if you use the -split operator instead of the Split() method you can simply daisy-chain it (again without using the pipeline):

$out = $in -replace 's' -split ' '

Upvotes: 5

San
San

Reputation: 236

try this

$in = "string with spaces"
$out = $in -split ' '  -replace 's'
echo $out

Upvotes: 2

Related Questions