Powershell Opening File Path with Spaces

自闭症网瘾萝莉.ら 提交于 2019-11-29 14:05:47

问题


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!


回答1:


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.




回答2:


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

 "`"$filepath`""



回答3:


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:


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\""




回答5:


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 + """"
}


来源:https://stackoverflow.com/questions/22840882/powershell-opening-file-path-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!