繁体   English   中英

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

[英]Call PowerShell script file from VBA In Windows 10

一段时间以来,我一直在使用此代码并且它以前有效

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:\Users\Future\Desktop\Hello World.ps1"""
Set wshShell = CreateObject("WScript.Shell")
Set wshShellExec = wshShell.Exec(strCommand)
strOutput = wshShellExec.StdOut.ReadAll

MsgBox strOutput
End Sub

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

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

StdOut:       
StdErr:       File C:\Users\Future\Desktop\Hello 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:\Users\Future\Desktop\Hello 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM