Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass path with spaces to script

I am trying to use PowerShell to call an EXE that is at a location/path containing spaces. When I call the script from the command line, the EXE's full path is not being passed to the script. Any ideas as to why this is happening?

PowerShell Script Contents (Untitled1.ps1)

Here is the entire script that gets called from the command line:

param(
    [string] $ParamExePath
)

function Run-CallThisExe {
    param(
        [string] $ThisExePath
    )

    Write-Host "ThisExePath: " "$ThisExePath"
    start-process -FilePath $ThisExePath
}

write-host "ParamExePath: " $ParamExePath

Run-CallThisExe -ThisExePath "$ParamExePath"

Command Line String

Here is the command line string being run from the PowerShell script's parent folder:

powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"

Output

Here is what is output after running the script

ParamExePath:  C:\path
ThisExePath:  C:\path

start-process : This command cannot be run due to the error: The system cannot
find the file specified.
At C:\sample\Untitled1.ps1:11 char:5
+     start-process -FilePath $ThisExePath
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
like image 697
Michael Avatar asked Sep 01 '15 19:09

Michael


2 Answers

Just change this:

powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"

To This:

powershell -file .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"

The -Command Parameter used to execute commands for example {Get-Date}

The -File Parameter used to Run .ps1 Script File

-Command
    Executes the specified commands (and any parameters) as though they were
    typed at the Windows PowerShell command prompt, and then exits, unless
    NoExit is specified. The value of Command can be "-", a string. or a
    script block.

-File
    Runs the specified script in the local scope ("dot-sourced"), so that the
    functions and variables that the script creates are available in the
    current session. Enter the script file path and any parameters.
    File must be the last parameter in the command, because all characters
    typed after the File parameter name are interpreted
    as the script file path followed by the script parameters.

Type Powershell /? to get full details on each Parameter

like image 93
Avshalom Avatar answered Oct 22 '22 17:10

Avshalom


A couple of other ways to call it:

powershell -command .\Untitled1.ps1 -NonInteractive "-ParamExePath 'C:\path with spaces\myapp.exe'"

powershell -command ".\Untitled1.ps1 -ParamExePath 'C:\path with spaces\myapp.exe'" -NonInteractive 
like image 24
dugas Avatar answered Oct 22 '22 15:10

dugas