I have a vbscript to call a PowerShell script in hopes of returning the PowerShell output to an HTA (HTML Application) GUI. Right now I just want to see if I can return the PowerShell output into a MsgBox in the vbscript. I am not having much luck with this.
VBScript Code:
Set shell = CreateObject("WScript.Shell")
return = shell.Run("powershell.exe -executionpolicy bypass -noprofile -file pathToScript\PowerShellToVBA.ps1", , true)
MsgBox return
PowerShell Code:
Clear-Host
return 50
I am trying to keep the return value extremely simple until it works. With this, I would expect the MsgBox to return '50', however it is returning '0' instead. Any ideas what im doing wrong?
I think you just want the exit command to get the return value:
VBScript
pscommand = ".\myscript.ps1; exit $LASTEXITCODE"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
rv = shell.Run(cmd, , True)
MsgBox "PowerShell returned: " & rv, vbSystemModal
Powershell
exit 50;
EDIT #1
Or if you want to grab a return string:
VBScript
pscommand = ".\myscript2.ps1"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
Set executor = shell.Exec(cmd)
executor.StdIn.Close
MsgBox executor.StdOut.ReadAll
Powershell
Write-Output '***SUCCESS***';
As a followup, using the VBScript above to output a string. In your PS script if you use eg
write-host "Error: some specific thing happened"
to set various error or success messages the
MsgBox executor.StdOut.ReadAll
will display all of what you write via write-host.
A helpful way to display the outcome of the PS script to your VBA user.
Just FYI.
Related
I wanted to know if it is possible to pass arguments to powershell via VBscript.
Here is my code and my investigation on this topic so far.
VBscript:
Dim pathvalue (pathvalue will dynamic path, which may have spaces in it. lets say path is "\\Server\search\File in some folder\Stack Overflow\")
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit -File \\server\Support\abhishek\Automation\SearchUtility.ps1 -Inputs " & PathValue
Set oShell = CreateObject("Wscript.Shell")
iResult = oShell.Run(sCmd, 1, true)
PS1.
Param([String] $Inputs)
$FolderPath = $Inputs;
echo "$FolderPath";
Expected result :
\\Server\search\File in some folder\Stack Overflow\
Actual Result :
\\Server\search\File
I tried different methods to pass the arguments ex. by putting it in single quotes, by putting 3 double Quotes but still it is not working.
Here is a code example:
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit -File \\server\Support\abhishek\Automation\SearchUtility.ps1 -Inputs " &"'" & PathValue & "'"
I got stuck for days and I haven't found a way to get this done. I need some help here. (I am new to Powershell)
Thanks in advance.
Try this. You don't need to build it in steps like this. I just did it this way to make it more readable. The last line is the critical part.
sCmd = "powershell.exe -ExecutionPolicy ByPass -noexit "
sCmd = sCmd & "-File \\server\Support\abhishek\Automation\SearchUtility.ps1 "
sCmd = sCmd & "-Inputs " & Chr(34) & PathValue & Chr(34)
If have created a VBS script that watches for new created processes like notepad.exe or calc.exe. When a new notepad or calc proces is found i like to do something in powershell with the found procesname.
The VBS script i created works fine when I manually edit the procesname in the VBS file, but when i try to use/pass the procesname form vbs (strName) to powershell I expect to see the procesname (notepad.exe), but instead the powershell window shows "strName".
I've been all over the internet to find a solution, without result.
My VBS file [start.vbs]
source: http://blogs.technet.com/b/heyscriptingguy/archive/2009/11/02/hey-scripting-guy-november-1-2009.aspx
arrProcesses = Array("calc.exe","notepad.exe")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
i = 0
Set colMonitoredProcesses = objWMIService. ExecNotificationQuery _
("Select * From __InstanceCreationEvent Within 5 Where TargetInstance ISA 'Win32_Process'")
Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
strProcess = LCase(objLatestProcess.TargetInstance.Name)
For Each strName in arrProcesses
If strName = strProcess Then
''Run Powershell file
'source: https://stackoverflow.com/questions/19156178/passing-arguments-to-powershell
Set WshShell = CreateObject("WScript.Shell")
''this works great
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""notepad.exe"" ")
'this doesnt
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")
'OR
'Trying to work arround it, with no result :(
RUNPSVAR="(" + """" +"Powershell.exe -file .\GetParamFromVBS.ps1 & """"" +strName +"""""" +""& " " +"""" +")"
wscript.Echo RUNPSVAR
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""RUNPSVAR"" ")
End If
Next
Loop
My Powershell File [GetParamFromVBS.ps1]
source: How to pass command-line arguments to a PowerShell ps1 file
param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + " "
}
write-host $Script:args
pause
Anyone any ideas?
Change:
WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")
To:
WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 '" & strName & "'")
Variables aren't string literals.
So something like this
a = "a string literal" & aVariableContainingAString
I need to pass a comma delimited parameter to a batch file via powershell and can't seem to get it to work. Here's how I call the batch file if I call it directly in powershell:
PS C:\Users\Mike> type zz.cmd
#echo off
echo/* = [%*}
echo/1 = [%1]
echo/2 = [%2]
echo/3 = [%3]
pause
PS C:\Users\Mike> cmd /c zz "q,w,e"
* = [q,w,e}
1 = [q]
2 = [w]
3 = [e]
Press any key to continue . . .
If I use cmd /c zz """q,w,e""" or cmd /c zz '"q,w,e"' I will get "q,w,e" for arg 1. This is good. However, I must call powershell using Invoke-Command. When doing this, the script doesn't work:
powershell.exe Invoke-Command -ScriptBlock { "cmd /c E:\\npoess\\oo\\WoD\\zzz" '"q,w,e"'}
Any idea how to get the powershell call from the command prompt to get "q,w,e" as one parameter to the batch file?
Thanks,
-Mike
this invoke-command without all the quotes works for passing a for me :
I think that the quotes around the variables passes the set as a string instead of separate values.
Invoke-Command -ScriptBlock {
cmd /c C:\scripts\zz.cmd q,w,e
}
I have one vbscript to execute a powershell script.
The powershell script simply append the result to a file.
Then after the powershell script execution complete and return to vbscript.
The vbscript will read content of the file and display it on console.
Unfortunately the powershell cannot generate the result file to be read by the vbscript.
If I change the line to ErrCode = objShell.run("powershell.exe -file writeFile.Ps1", 0),
The powershell script can generate the result file.
But the vbscript can never display the content of the result file correctly or it is corrupted.
If I open the result file from Notepad, I can view the content correctly.
Do you have any idea what is the problem behind?
Here are the source code:
Source code for readFile.vbs:\
resultFile = "writeFile.Ps1.txt"
set objShell = CreateObject("WScript.Shell")
ErrCode = objShell.run("powershell.exe -nologo -command writeFile.Ps1", 0)
Set objReadFile = CreateObject("Scripting.FileSystemObject")
Set strLines = objReadFile.OpenTextFile(resultFile, 1)
Do While Not strLines.AtEndOfStream
strLine = strLines.ReadLine()
WScript.Echo strLine
Loop
Set objReadFile = Nothing
Source code for writeFile.Ps1:
$ResultFilePath = "writeFile.Ps1.txt"
If (Test-Path $ResultFilePath) {
Remove-Item $ResultFilePath
}
Get-Date | out-file $ResultFilePath
Exit 0
Thanks.
On the Out-File, try using the parameter "-Encoding ASCII". By default Out-File outputs in Unicode.
Either make PowerShell create the file with ASCII encoding as Keith Hill suggested:
Get-Date | Out-File $ResultFilePath -Encoding ASCII
or open it as Unicode in VBScript:
Set strLines = objReadFile.OpenTextFile(resultFile, 1, False, -1)
I'm running PS scripts from VBScript and would like to throw exception in VBScript if there were errors in PS. This is the VBScript code I use to run PowerShell:
Option Explicit
Dim oShell, appCmd
Set oShell = CreateObject("WScript.Shell")
appCmd = "powershell set-executionpolicy unrestricted -force; c:\3.ps1"
oShell.Run appCmd, 4, true
This is my PS script:
throw "I'm exception"
I've tried general VBScript catch:
if( Err.number <> 0 ) then
Err.raise()
end if
but it doesn't seem to work. I would love to use only PS and get rid of VBScript altogether, but it's another application that is running VBs and it only supports VBs. Any ideas?
I could write exception in file in PS and then from VBs check if file exist and throw exception, but I hope there's a better way.
Thanks
In the Powershell script use
exit $MyErrorLevel
Where $MyErrorLevel is your own code you will detect with VBS.
In VBS the WShell object Run method will return the exit code from PowerShell.
Example VBS script:
Option Explicit
Dim oShell, appCmd
Dim intReturnCode
Set oShell = CreateObject("WScript.Shell")
appCmd = "powershell.exe -File c:\Test.ps1"
intReturnCode = oShell.Run(appCmd, 4, true)
MsgBox intReturnCode
Example PS script (C:\Test.ps1):
try {
1 / $null
} catch {
exit 1
}
exit 0