Try this the Powershell function below to run a powershell command and return the output. The code outputs the result of the command to a temporary file, waits for the command to complete, and returns the output.
The Powershell function uses sub WaitFile to wait for the output file to be completed, which signals completion of the powershell command, and uses the Windows sleep function to wait 100ms when polling.
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Function Powershell(Command As String) As String
'Runs powershell command and returns output
Dim FilePath As String
Dim OutFile As String
Dim fso As Object
'Generate output file name
FilePath = ThisWorkbook.Path
Set fso = CreateObject("Scripting.FileSystemObject")
OutFile = FilePath & "\" & fso.GetTempName()
Set fso = Nothing
'Delete output file if it exists
DelFile OutFile
'Add output file to command
Command = SPrintF("%s | out-file -FilePath %s -Encoding ASCII", Command, OutFile)
'Run command
Shell SPrintF("Powershell ""%s""", Command), vbMinimizedNoFocus
'Wait for temp file to appear
WaitFile OutFile
'Gather results from temp file
Powershell = GetFile(OutFile)
'Delete output file if it exists
DelFile OutFile
End Function
Sub WaitFile(FileName As String, Optional TimeOutSecs As Long = 60)
'Returns entire contents of file
Dim fhan As Long
Dim s As String
Dim StartTime As Date
On Error Resume Next
'Initialise start time
StartTime = Now
'Wait for file to appear (or time out)
Do While FileLen(FileName) = 0
Sleep 100
DoEvents
If DateDiff("s", StartTime, Now) > TimeOutSecs Then Exit Do
Loop
End Sub