在Windows 10中从VBA调用PowerShell脚本文件



从一段时间以来,我一直在使用这段代码,它在之前就已经工作了

Sub Call_PowerShell_Script_File_From_Excel_VBA()
'Windows PowerShell ISE >> New Script >> Create 'Hello World.ps1'
'    echo "Hello World"
'    $x = 1 + 1
'    echo $x
'----------------------------------------------------------------
Dim wshShell        As Object
Dim wshShellExec    As Object
Dim strCommand      As String
Dim strOutput       As String
strCommand = "Powershell.exe -File ""C:UsersFutureDesktopHello World.ps1"""
Set wshShell = CreateObject("WScript.Shell")
Set wshShellExec = wshShell.Exec(strCommand)
strOutput = wshShellExec.StdOut.ReadAll
MsgBox strOutput
End Sub

我在Windows7上工作,代码没有问题。安装Windows 10后,我发现代码不起作用,我收到了没有输出的空白消息有什么想法吗??

**在测试Tim的代码时,我收到了以下消息

StdOut:       
StdErr:       File C:UsersFutureDesktopHello World.ps1 cannot be loaded 
because running scripts is disabled on this system. For 
more information, see about_Execution_Policies at 
https:/go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo          : SecurityError: (:) [], 
ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess

试试这个,看看你得到了什么:

Sub Call_PowerShell_Script_File_From_Excel_VBA()
'Windows PowerShell ISE >> New Script >> Create 'Hello World.ps1'
'    echo "Hello World"
'    $x = 1 + 1
'    echo $x
'----------------------------------------------------------------
Dim wshShell        As Object
Dim wshShellExec    As Object
Dim strCommand      As String
Dim strOutput
strCommand = "Powershell.exe -File ""C:UsersFutureDesktopHello World.ps1"""
Set wshShell = CreateObject("WScript.Shell")
Set wshShellExec = wshShell.Exec(strCommand)
strOutput = wshShellExec.StdOut.ReadAll()
Debug.Print "StdOut:", strOutput
strOutput = wshShellExec.StdErr.ReadAll()
Debug.Print "StdErr:", strOutput

End Sub

最新更新