如何让VBA调用时打开指定版本PowerShell 7.3.6.0?
如何让VBA调用PowerShell 7.3.6.0
原来的powershell命令默认启动的是Windows PowerShell(最高版本为5.1,常被误称v1),而PowerShell 7.x是独立的分支,无法通过powershell -Version参数调用,必须直接指定它的执行程序。
以下是两种可行的解决方案:
方法1:使用pwsh命令(推荐)
PowerShell 7安装后,默认会将pwsh.exe添加到系统环境变量PATH中,直接用pwsh代替powershell即可:
修改后的VBA代码:
Sub RunPowershell7() Set wShell = CreateObject("WScript.Shell") ' 使用pwsh调用PowerShell 7 Set wShellResult = wShell.Exec("pwsh -Command (Get-Volume -DriveLetter C).SizeRemaining") MsgBox wShellResult.StdOut.ReadAll End Sub
注:加上
-Command参数更规范,明确指定要执行的命令,避免潜在解析问题。
方法2:指定完整路径(适用于PATH未配置的情况)
如果pwsh命令无法识别,直接使用PowerShell 7.3.6.0的完整安装路径,默认路径一般为C:\Program Files\PowerShell\7\pwsh.exe:
修改后的VBA代码:
Sub RunPowershell7ByPath() Set wShell = CreateObject("WScript.Shell") ' 指定PowerShell 7的完整路径 Set wShellResult = wShell.Exec("""C:\Program Files\PowerShell\7\pwsh.exe"" -Command (Get-Volume -DriveLetter C).SizeRemaining") MsgBox wShellResult.StdOut.ReadAll End Sub
注:路径包含空格,需要用双引号包裹,VBA中要转义为两个双引号
""。
内容的提问来源于stack exchange,提问作者96ask
相关产品推荐
相关产品推荐

