如何在 ps 脚本路径有空格且路径源自 %~dp0% 时从批处理文件运行 powershell 脚本

Joe*_*Joe 2 powershell batch-file

我有一个批处理文件 Install.bat,它调用 GetVersion.ps1 powershell 脚本。这两个脚本位于同一个文件夹(C:\Install_Media)中,我通过获取批处理文件所在的目录(使用 %~dp0%)来调用 powershell 脚本。

如果这些文件所在的路径中没有空格,则以下代码效果很好。如果路径中有空格,则 shellscript 不会被执行(例如 C:\Install Media)。脚本停止说术语“C:\Install”不被识别为 cmdlet、函数、脚本的名称。

@ECHO OFF
set SRC_DIR=%~dp0%
Powershell set-executionPolicy remotesigned
Powershell %SRC_DIR%\GetSLMClientVersion.ps1
Powershell set-executionPolicy restricted
Run Code Online (Sandbox Code Playgroud)

错误截图

Ans*_*ers 5

参数扩展仅%在表达式的开头使用单个字符。此外,您不需要来回更改执行策略。powershell.exe有一个用于临时覆盖执行策略的参数。正如TheIncorrigible1在评论中指出的那样,最好通过将路径放在引号中来处理路径中的空格。

将您的代码更改为:

@echo off
powershell.exe -ExecutionPolicy Bypass -File "%~dp0\GetSLMClientVersion.ps1"
Run Code Online (Sandbox Code Playgroud)