Home » Using Invoke-Expression in PowerShell With Spaces in Paths

Using Invoke-Expression in PowerShell With Spaces in Paths

One of the early bugs found in Exchange Analyzer was an error being thrown when the final HTML report was displayed. I had been developing the script in a folder path of X:\Scripts\ExchangeAnalyzer.  In other words, a path with no spaces. Some of the early users then tried to run the script from a path such as X:\Scripts\Exchange Analyzer and reported errors.

Here’s an example of what went wrong. Let’s say we’ve got an HTML file in C:\Scripts, and it’s called “Test Document.html”. If I use Invoke-Expression to launch that HTML file, an error will be thrown:

As it turns out, Invoke-Expression doesn’t handle spaces in paths like that. But there’s a couple of easy fixes that you can use.

One fix is to use the following command instead:

That will also work if the path to the document is stored in a variable.

The other option is to escape the spaces in the path, for example:

The first option is probably better, as it doesn’t require you to modify the existing variable or set a new variable for the path with escaped spaces. But either option should solve the problem of using Invoke-Expression with spaces in the path.

Paul is a technical writer, published author, and Pluralsight trainer living in Brisbane, Australia. He is a Microsoft MVP and runs the Practical 365 website. Say hi on Twitter.
Category: Code

Leave a Reply

Your email address will not be published. Required fields are marked *