If I have a string like so:
$String = "Hello world"
and attempt to prefix another string into it by:
$String | % {"Page 1 = ($_.trim())"}
I get back:
Page 1 = (Hello world.trim())
I have tried a few other variations, the only one that worked is:
$String | % {($_.trim())}
Which is not ideal, as I need to prefix a string to multiple lines of text files. Any help would be appreciated
CodePudding user response:
You're looking to invoke an expression embedded in a string, that's exactly what the Subexpression Operator $( )
is for. As aside, your .Trim()
wouldn't do anything on that example string because it can only trim exceeding leading or trailing whitespace.
If your string looked like this then Trim()
would be perfect:
$String = " Hello World "
$String | ForEach-Object { "Page 1 = $($_.Trim()')" }
However, it seems you actually want to remove the exceeding white space from the middle of the string, in that case you can use -replace
:
$String = "Hello World"
$String | ForEach-Object { "Page 1 = $($_ -replace '\s')" }
# if you want to leave a white space in the middle
$String | ForEach-Object { "Page 1 = $($_ -replace '\s ', ' ')" }