Recently I was updating the CD of a project and came across a peculiar issue with Invoke-Expression not executing a script when the file path contained spaces.
The CD agent had previously been running the script in a folder like C:\ApplicationDelivery\Scripts\Release\<Version>
however to keep the artefacts of the CD agent all together I wanted the script to be run as part of the agent's path; which were all installed within C:\Program Files\Agents\etc...
. When testing the change, the release scripts were not running as expected, which was strange as I'd only changed the location the scripts were running from.
After a small debugging session I found the culprit. Here's an overview of what went wrong. Let's say we have a script called Test Script.ps1
in the folder C:\SourceCode\Scripts
and we attempt to run that script using Invoke-Expression
, an error will be thrown:
PS C:\SourceCode\Scripts> Invoke-Expression ".\Test Script.ps1"
.\Test : The term '.\Test' is not recognized as the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
Strange right, almost everything else in PowerShell when using brackets account for the spaces. Luckily there is something we can do about this.
The fix is to use the following command instead:
PS C:\SourceCode\Scripts> Invoke-Expression "& '.\Test Script.ps1'"
For scenarios where you require the path to be stored in a variable will also work:
PS C:\SourceCode\Scripts> $scriptPath = "C:\SourceCode\Scripts\Test Script.ps1"
PS C:\SourceCode\Scripts> Invoke-Expression "& '$scriptPath'"
Comments
Be the first to comment!