简体   繁体   中英

Call PowerShell script file from VBA In Windows 10

Since a time, I was using this code and it worked before

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

I was working on Windows 7 and the code was with no problem. After installing Windows 10, I found the code not working and I got blank message with no output Any ideas ??

** When testing Tim's code I got this message

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

Try this and see what you get:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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