Reputation: 385
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
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
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
Reputation: 236
try this
$in = "string with spaces"
$out = $in -split ' ' -replace 's'
echo $out
Upvotes: 2