Powershell Opening File Path with Spaces

2019-02-09 22:15发布

Im my PS script I want to be able to run another script in another PS instance by doing the following:

$filepath = Resolve-Path "destruct.ps1"

start-process powershell.exe "$filepath"

destruct.ps1 is in the same folder as this script

However when running this script in a location which includes spaces ("C:\My Scripts\") i will get the following error:

The term 'C:\My' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.

I know by using a '&' with the Invoke-Expression method solves this problem, how can i do the same but by using the start-process method?

Thanks soo much for any help!

5条回答
Summer. ? 凉城
2楼-- · 2019-02-09 22:56

File name might contain spaces, so preserve spaces in full path:
Notepad++ exec command:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" "& \"$(FULL_CURRENT_PATH)\""

same from command prompt:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" "& \"C:\a_work\Systems\name with spaces.ps1\""

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-09 22:57

I am answering here for a general scenario.

If you need to navigate to a folder for example C:\Program Files from the Powerhsell, the following command won't work as it has white space in between the path.

cd C:\Program Files

Instead embed the path with double quotes as like the below.

cd "C:\Program Files"

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-09 22:59

You can add escaped double quotes so that you pass a quoted argument:

 "`"$filepath`""
查看更多
聊天终结者
5楼-- · 2019-02-09 23:03

Just in case [string]$shipno (which is path & file name) comes in including spaces the following allows it to be passed to -FilePath successfully:

if ($shipno.contains(" ") -eq $true) {
   $shipno = """" + $shipno + """"
}
查看更多
叛逆
6楼-- · 2019-02-09 23:06

try this:

 start-process -FilePath powershell.exe -ArgumentList "-file `"$filepath`""

edit after comments:

start-process -FilePath powershell.exe -ArgumentList "-file `"$($filepath.path)`""

side note:

$filepath is a [pathinfo] type and not a [string] type.

查看更多
登录 后发表回答