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

Excel 在Windows 10中从VBA调用PowerShell脚本文件,excel,vba,powershell,Excel,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 '------------------------------------------

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

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
我在Windows7上工作,代码没有问题。 安装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

你能手动运行那个脚本吗?是的,这让我很困惑。非常感谢。我已经把结果放在主要的帖子里了。如何在系统上启用它?不知道-只是指出问题。如果你在公司的电脑上,那就问问你的IT人员。如果你在家,那么从这里开始:非常感谢你的帮助。通过以管理员身份打开PowerShell,然后使用
设置ExecutionPolicy Unrestricted
然后也使用此命令
设置ExecutionPolicy-Scope CurrentUser-ExecutionPolicy ByPass-Force