如何将带空格的路径传递给脚本

时间:2015-09-01 19:25:51

标签: powershell command-line

我正在尝试使用PowerShell来调用位于包含空格的位置/路径的EXE。当我从命令行调用脚本时,EXE的完整路径没有传递给脚本。关于为什么会发生这种情况的任何想法?

PowerShell脚本内容(Untitled1.ps1)

以下是从命令行调用的整个脚本:

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"

命令行字符串

以下是从PowerShell脚本的父文件夹运行的命令行字符串:

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

输出

以下是运行脚本后输出的内容

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

3 个答案:

答案 0 :(得分:5)

只需改变一下:

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

To This:

-Command

用于执行命令的-File参数,例如{Get-Date}

用于运行.ps1脚本文件的-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. 参数

Powershell /?

输入h(2n) - h(n) = 1/(n/2 + 1) + 1/(n/2 + 2) + ... + 1/n < 1/(n/2) + 1/(n/2) + ... + 1/(n/2) = 1, 以获取每个参数的完整详细信息

答案 1 :(得分:2)

其他几种称呼方式:

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

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

答案 2 :(得分:0)

请注意,如果将具有尾部反斜杠的文件夹路径传递给Powershell,它将无法处理该路径。例如-ParamFolder“ C:\ project文件夹\ app \ bin调试\”。参数字符串以结尾加双引号结尾。因此,当您尝试将文件名附加到文件名时,最终会得到类似C:\ project folder \ app \ bin debug“ Filename.txt的内容。在这种情况下,您必须在末尾添加第二个反斜杠。 / p>

相关问题