1

In PowerShell I am trying to find a way to remove the text from an output of text and a String.

Write-Host 'File located at C:\'$Fileline.FilePath -

I get an output of

c:\ program files\path

The space between c:\ and "Program files" is what I want to remove. Do I have to convert the text to a string, and then output it as two strings and then remove the spaces?

1
  • Write-Host "File located at C:\$($Fileline.FilePath)" Commented Sep 26, 2018 at 13:27

2 Answers 2

3

This is happening because you are passing multiple strings to Write-Host, which it is then joining with spaces. This behaviour is somewhat unique to Write-Host.

You can meet your need by sending a single double quoted string to Write-Host, which you can then put your variable inside and it will be expanded. However because you are accessing a property of your variable, you need to wrap it in a sub-expression: $():

Write-Host "file located at C:\$($Fileline.FilePath) -"
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly for me, but why did you include the space - at the end of the line?
I was just mirroring what was in your original code, but if the " -" part shouldn't be there then just remove it.
1

Try using the PowerShell -f formatting operator:

Write-Host ("File located at C:\{0} -" -f $FileLine.FilePath)

There's good info on -f at SS64 and at TechNet

4 Comments

This did not work for me. It appears that the -f is assumed to be the start of "-foregroundcolor" option. it gave the following message Write-Host : Cannot bind parameter 'ForegroundColor'.
This would work as it would make -f operate on the string as Jeff intended vs being treated like a parameter of Write-Host: Write-Host ("File located at C:\{0} -" -f $FileLine.FilePath)
Hmmm... I've never seen that happen, but you can force the correct interpretation with Write-Host ("File located at C:\{0} -" -f $FileLine.FilePath).
FWIW I always have to use braces when I do this because of the parameter interpretation issues. It does make sense that you would have to in a normal environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.