How to call a PowerShell file with parameters using VBScript - powershell

Greetings everyone and Happy New Year.
I just learned about PowerShell two days ago and it shows. I am trying to make custom Balloon tips and didn't what to make separate ps1 scripts for every possible event. What I needed was a ps1 with parameters.
I found this bit of code at this site:
GitHub Invoke-BalloonTip
And I call successfully call it from the PS window with:
. .\Invoke-BalloonTip.ps1
Invoke-BalloonTip -Message 'Message' -Title 'Title' -MessageType Info
However, I need to call this from a VBScript. I have tried:
Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell -command . c:\PowerShellTest\Invoke-BalloonTip.ps1" & Invoke-BalloonTip -Message 'Invoked' -Title 'Invoked' -MessageType Info)
And
Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell -command ""& { . c:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message 'Message' -Title 'Title' MessageType Info }""")
And a few others with unsatisfactory results. These two examples are the only ones that show no errors in the PS window when it runs. With these two examples the PS window will show briefly and display no error messages but no Balloon Tip will display.
I am certain it is a syntax issue but I am out of ideas as to what it may be. Any ideas or suggestions are welcome and appreciated.

I think the issue is with the original Invoke-BalloonTip.ps1 as it tries to use the System.Windows.Forms.ToolTipIcon type before it is available (via loading System.Windows.Forms). Adding it earlier in your command should fix things (though it does seem a bit hacky):
Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell.exe -command ""& {Add-Type -AssemblyName System.Windows.Forms;. C:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message ""Message"" -Title ""Title"" -MessageType Info}""")
Invoke-BalloonTip.ps1 works straight away in the PowerShell ISE as the correct assembly is already loaded by default, but not so in powershell.exe or VSCode.

For the sake of anyone else who comes here with a similar problem, this will not work if there are spaces in your Message or Title. To fix it, I surrounded the strings with single quotes:
objShell.run("powershell.exe -command ""& {Add-Type -AssemblyName System.Windows.Forms;. C:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message ""'Message with Space'"" -Title ""'Title With Space:'"" -MessageType info}""")

You can use this code.
Dim strTitle, srtContext, strCommang
strTitle = "Title"
srtContext = "Text"
strCommang = "powershell.exe -executionpolicy bypass -command " & _
"[reflection.assembly]::loadwithpartialname('System.Windows.Forms')" & vbNewLine & _
"[reflection.assembly]::loadwithpartialname('System.Drawing')" & vbNewLine & _
"$notify = new-object system.windows.forms.notifyicon" & vbNewLine & _
"$notify.icon = [System.Drawing.SystemIcons]::Information" & vbNewLine & _
"$notify.visible = $true" & vbNewLine & _
"$notify.showballoontip(10,'" & strTitle & "','" & srtContext & "',[system.windows.forms.tooltipicon]::None)"
Set objShell = CreateObject("Wscript.shell")
objShell.Run strCommang, 0
Set objShell = Nothing

Related

Embed VBScript in PowerShell Script - One File

I recently learned a lot messing with batch + VBScript hybrid scripts and while it was great learning and works, it's time to learn PowerShell more thoroughly. But, my favorite part of Batch/VBScript solution is that I can create a single script.cmd file to distribute.
Is there any sort of solution with PowerShell/VBScript? Ideally I think I'd prefer a .ps1 script with embedded VBScript, but interested in knowing my options.
There seems to be some confusion regarding the goal.
One Single File (This is the most important part)
Extension either .ps1 or .vbs
Both POWERSHELL and VBScript inside single file
Bonus:
No writing to external file
Prefacing each line
Having to escape special characters in code
Encoding entire sections of script (overhead CPU intensive operations)
Here is a thoeretical example:
script.{ps1/vbs}:
<!-- : Begin PS1 script
$strString = "Hello PowerShell"
write-host $strString
cscript //nologo "%~f0?.wsf" //job:HELLOWORLD
exit /b
PAUSE
----- Begin wsf script --->
<package>
<job id="HELLOWORLD">
<script language="VBScript">
MsgBox "Hello World VBS"
</script>
</job>
<job id="VBS">
<script language="VBScript">
'Second Script!
</script>
</job>
</package>
Something like this -->
https://stackoverflow.com/a/9074483/5079799
<!-- : Begin batch script
#ECHO OFF
CLS
cscript //nologo "%~f0?.wsf" //job:HELLOWORLD
exit /b
PAUSE
----- Begin wsf script --->
<package>
<job id="HELLOWORLD">
<script language="VBScript">
MsgBox "Hello World"
</script>
</job>
<job id="VBS">
<script language="VBScript">
'Second Script!
</script>
</job>
</package>
Create the VBS script as usual. Save in some location and then convert it into Base64. Byte encoding is used so that this will work on binary files too, and overcomes character encoding issues. Like so,
$Content = Get-Content -Path C:\temp\myScript.vbs -Encoding Byte
$Base64 = [System.Convert]::ToBase64String($Content)
$Base64 | Out-File c:\temp\myScript.b64
Then, in your Powershell script, include the encoded version of the VBS script. Convert Base64 back into string and write it into a file. Finally, call cscript to run the .vbs.
$Base64 = "ZgB1AG4AYwB0AGkAbwBuACAAR..."
$Content = [System.Convert]::FromBase64String($Base64)
Set-Content -Path $env:temp\myScript.vbs -Value $Content -Encoding Byte
& cscript /nologo $env:temp\myScript.vbs
Another an option is to embed the VBScript in a here-string like so,
# Paste the VBS in a here string
$Content = #'
dim foo
...
'#
Set-Content -Path $env:temp\myScript.vbs -Value $Content
& cscript /nologo $env:temp\myScript.vbs
Perhaps, you mean create a .ps1 script file and run it from vbscript ?
If so, here is an example named as Compress_Archive_by_Extension.vbs
Remark : Compress-Archive is only available with PS v4
Option Explicit
Dim Title,ArrExt,Ext
Title = "Compress Archive With Powreshell And Vbscript by Hackoo 2020"
REM We define an array of extensions for archiving !
ArrExt = Array("vbs","vbe","cmd","bat","ps1","js","jse","lnk")
REM Looping thru extensions defined from our array in order to zip and archive them,
REM so you can add or remove what you want as extension in the array above !
For each Ext in ArrExt
Call Compress_Archive("%Temp%\*."& Ext,"Temp_Archive_"& Ext)
Call Compress_Archive("%AppData%\*."& Ext,"AppData_Archive_"& Ext)
Call Compress_Archive("%LocalAppData%\*."& Ext,"LocalAppData_Archive_"& Ext)
Call Compress_Archive("%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup\*."& Ext,"ProgramData_Archive_"& Ext)
Call Compress_Archive("%UserProfile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\*."& Ext,"UserProfile_Archive_"& Ext)
Next
MsgBox "Archive Script is completed !",vbInformation,Title
'---------------------------------------------------------------------
REM https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/compress-archive?view=powershell-5.1&redirectedfrom=MSDN
Sub Compress_Archive(Source,Destination)
Const ForWriting = 2
Dim fs,Ws,ts,Ret,PSFile,ByPassPSFile
Set fs = CreateObject("Scripting.FileSystemObject")
Set Ws = WScript.CreateObject("WScript.Shell")
Source = Ws.ExpandEnvironmentStrings(Source)
Destination = Ws.ExpandEnvironmentStrings(Destination)
PSFile = Ws.ExpandEnvironmentStrings("%Temp%") & fs.GetTempName & ".ps1"
ByPassPSFile = "PowerShell -ExecutionPolicy bypass -noprofile -file "
Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
ts.WriteLine "Compress-Archive -Path " & DblQuote(Source) &_
" -Update -CompressionLevel Optimal -DestinationPath "& DblQuote(Destination)
ts.Close
Ret = Ws.run(ByPassPSFile & PSFile,0,True)
If fs.FileExists(PSFile) Then fs.DeleteFile(PSFile)
End Sub
'---------------------------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'---------------------------------------------------------------------
Second example : To download an image from site : Download_File.vbs
Option Explicit
Dim URL,Ws,ByPassPSFile,PSFile,MyCmd,Result
URL = "https://cdn2.unrealengine.com/Fortnite%2FBoogieDown_GIF-1f2be97208316867da7d3cf5217c2486da3c2fe6.gif"
Set Ws = CreateObject("wscript.Shell")
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
ByPassPSFile = "cmd /C PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
MyCmd = "$source = " & DblQuote(URL) & VbCrlF
MyCmd = MyCmd & "$Filename = [System.IO.Path]::GetFileName($source)" & VbCrlF
MyCmd = MyCmd & "$dest = " & DblQuote("$env:temp\$Filename") & VbCrlF
MyCmd = MyCmd & "$wc = New-Object System.Net.WebClient" & VbCrlF
MyCmd = MyCmd & "$wc.DownloadFile($source,$dest)" & VbCrlF
MyCmd = MyCmd & "Start-Process $dest"
Call WriteMyPSFile(MyCmd)
Result = Ws.run(ByPassPSFile & PSFile,0,True)
'----------------------------------------------------------------------------------------
Sub WriteMyPSFile(strText)
Dim fs,ts,PSFile
Const ForWriting = 2
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'----------------------------------------------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'----------------------------------------------------------------------------------------
EDIT : 21/08/2020 # 20:45
Here is a "pseudo-hybrid" because it use a temporary file to be executed :
inspired from #vonPryz answer.
You can save it as Test.ps1 and execute from PowerShell ISE
$VBS_Content = #'
Dim http, WAN_IP
Set http = CreateObject( "MSXML2.ServerXmlHttp" )
http.Open "GET", "http://icanhazip.com", False
http.Send
WAN_IP = http.responseText
wscript.echo "WAN_IP : " & WAN_IP
'#
Set-Content -Path $env:temp\myScript.vbs -Value $VBS_Content
& wscript.exe $env:temp\myScript.vbs
$url = "https://externals.lesechos.fr/medias/2019/04/26/2262811_pourquoi-salto-le-futur-netflix-francais-devra-seuropeaniser-195514-1.jpg"
#https://stackoverflow.com/questions/35813186/extract-the-filename-from-a-path
$output = $env:temp + "\" + $url.Split("/")[-1]
$start_time = Get-Date
Try {$wb = (New-Object System.Net.WebClient).DownloadFile($url,$output)}
Catch {
Write-Host "Error from $url ! " -ForegroundColor Red -BackgroundColor Yellow
Write-Host "Message: [$($_.Exception.Message)"] -ForegroundColor Red -BackgroundColor Yellow
}
Write-Output "Running Script Time taken is : $((Get-Date).Subtract($start_time).Seconds) second(s)"
Start-process $output
Another simple example :
$VBS_Content = #'
MsgBox "This a simple MsgBox from Vbscript"
'#
$TmpVBS="$env:temp\myScript.vbs"
SC $TmpVBS $VBS_Content
wscript.exe $TmpVBS
Echo 'Hello World from Powershell !'
Here is my final answer, I haven't tested with anything super complicated, so not sure how it would handle things like special characters...
#https://stackoverflow.com/questions/63514534/embed-vbscript-in-powershell-script-one-file
#######################Begin VBS1#######################
###JOB_A START###
$VBS_Content_Job_A = #'
MsgBox "This a simple MsgBox from Vbscript (Job_A)"
'#
###JOB_A END###
###JOB_B START###
$VBS_Content_Job_B = #'
MsgBox "This a simple MsgBox from Vbscript (Job_B)"
'#
###JOB_B END###
#######################Begin PS1#######################
ECHO 'Hello World from Powershell !'
PAUSE
ECHO "Running VBS Now"
PAUSE
###VBS CALL START###
$VBSJob=$VBS_Content_Job_A
$TmpVBS="$env:temp\myScript.vbs"
Remove-Item $TmpVBS -ErrorAction SilentlyContinue
SC $TmpVBS $VBSJob
cscript //nologo $TmpVBS
Remove-Item $TmpVBS -ErrorAction SilentlyContinue
###VBS CALL END###
ECHO "Some More PowerShell"
PAUSE
ECHO "I need anoter VBS Script"
PAUSE
###VBS CALL START###
$VBSJob=$VBS_Content_Job_B
$TmpVBS="$env:temp\myScript.vbs"
Remove-Item $TmpVBS -ErrorAction SilentlyContinue
Set-Content -Path $TmpVBS -Value $VBSJob
cscript //nologo $TmpVBS
Remove-Item $TmpVBS -ErrorAction SilentlyContinue
###VBS CALL END###
ECHO "All Done!"
PAUSE
You can embed VB.NET code into powershell code with TypeDefinition:
$code = #"
Imports System
Namespace MyNameSpace
Public Class Responder
Public Shared Sub StaticRespond()
Console.WriteLine("Static Response")
End Sub
Public Sub Respond()
Console.WriteLine("Instance Respond")
End Sub
End Class
End Namespace
"#
# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
Add-Type -TypeDefinition $code -Language VisualBasic;
}
[MyNameSpace.Responder]::StaticRespond();
$instance = New-Object MyNameSpace.Responder;
$instance.Respond();
Not exactly vbscript but is a good solution.

How do I run a .ps1 file via a .vbs file in the same folder?

The following files are in the same folder.
Testing.cmd
Toast notification.ps1
Run [Toast notification].vbs
When I run Toast notification.ps1, it works. However, when I run Run [Toast notification].vbs, the .ps1 file is not run.
The following is the PowerShell script:
[reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[reflection.assembly]::loadwithpartialname("System.Drawing")
# notify.icon type: Information, Warning or Error.
$notify = new-object system.windows.forms.notifyicon
$notify.icon = [System.Drawing.SystemIcons]::Information
$notify.visible = $true
$notify.showballoontip(10,"", "The CPU is hot.",
[system.windows.forms.tooltipicon]::None)
$notify.dispose()
The following is the VBScript:
Path = split(wscript.scriptFullName, wscript.scriptname)(0)
Item1 = Path & "Toast notification.ps1"
Item2 = Path & "Testing.cmd"
Set Action = CreateObject("Wscript.shell")
Action.run ("powershell -executionpolicy bypass -file ""& Item1 &""")
Action.run ("""" & Item2 & ""), 0
When I double-click on the VBScript file, the .ps1 file is not run. The "Path" can be used to run Testing.cmd, but I cannot make it work with a .ps1 file. How can I fix the problem? The following is the Testing.cmd file:
(ncpa.cpl)
When you run the PowerShell script it should look more like this:
Option Explicit
Dim Path : Path = split(wscript.scriptFullName, wscript.scriptname)(0)
Dim Item1 : Item1 = Path & "Toast notification.ps1"
Dim Item2 : Item2 = Path & "Testing.cmd"
Dim Action : Set Action = CreateObject("Wscript.shell")
Action.run "powershell -executionpolicy bypass -file " & chr(34) & Item1 & chr(34), 0, true
Action.run "cmd /c " & chr(34) & Item2 & chr(34), 0, true
Set Action = Nothing
The chr(34) represents quotes in case your path contains spaces. I'd also recommend more error checking, and checking that the files exist etc. The above example hides the PowerShell and CMD windows too...
You don't need 3 files to execute those commands, just, create one vbscript file.
So, refer to this,
You can do something like this :
Option Explicit
Dim Ws,Ret,ByPassPSFile,PSFile
Set Ws = CreateObject("wscript.Shell")
ByPassPSFile = "cmd /c PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
Call WritePSFile("Warning","10","'The CPU is hot !'","'The CPU is hot '","'Warning'","10")
Ret = Ws.run(ByPassPSFile & PSFile,0,True)
Ret = Ws.run("cmd /c ncpa.cpl",0,True)
'------------------------------------------------------------------------------------------------------------
Sub WritePSFile(notifyicon,time,title,text,icon,Timeout)
Const ForWriting = 2
Dim fso,ts,strText
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(PSFile,ForWriting,True)
strText = strText & "[reflection.assembly]::loadwithpartialname('System.Windows.Forms') | Out-Null;" & VbCrlF
strText = strText & "[reflection.assembly]::loadwithpartialname('System.Drawing') | Out-Null;" & VbCrlF
strText = strText & "$notify = new-object system.windows.forms.notifyicon;" & VbCrlF
strText = strText & "$notify.icon = [System.Drawing.SystemIcons]::"& notifyicon &";" & VbCrlF
strText = strText & "$notify.visible = $true;"
strText = strText & "$notify.showballoontip("& time &","& title &","& text &","& icon &");" & VbCrlF
strText = strText & "Start-Sleep -s " & Timeout &";" & VbCrlF
strText = strText & "$notify.Dispose()"
ts.WriteLine strText
End Sub
'-----------------------------------------------------------------------------------------------------------
There's also this nifty trick to start any PowerShell script with a generic batch (CMD). The trick is to name the batch like the PowerShell script, e.g. MyPS_Script.cmd and MyPS_Script.ps1. It even allows to pass arguments to the script via the batch
Batch:
#ECHO OFF
REM *****
REM * Wrapper CMD to start the PowerShell script of the same name
REM * I.e. if the script is named ServiceRestart.ps1, then the
REM * CMD needs to be named ServiceRestart.cmd
REM *****
PowerShell.exe -Command "& '%~dpn0.ps1' %1 %2 %3 %4 %5 %6 %7"
PAUSE
PS Script demonstration
ForEach ($Arg In $Args) {
Write-Host "Arguments from cmd" $Arg
}

Command Encoded in Powershell FAIL

I discovered that the command uncoded bad, but I do not understand what is wrong:
My Code :
$command = "(New-Object System.Net.WebClient).DownloadFile('http://localhost/update_program.exe','updater.exe'); Start-Process 'updater.exe'"
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
echo $encodedCommand
Return
KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGU
AbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQAcAA6AC8ALwBsAG8AYwBhAG
wAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAGUAeABlACcALAAnAHUAcABkA
GEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAnAHUAcABk
AGEAdABlAHIALgBlAHgAZQAnAA==
I try :
powershell -encodedCommand KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQAcAA6AC8ALwBsAG8AYwBhAGwAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAGUAeABlACcALAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnAA==
Return :
Editor's note: The symptom below is inconsistent with the code above, which is correct. There may not be a problem left to solve.
Missing expression after unary operator '-'.
In line: 1 Character: 2
+ - < <<< encodeCommand KABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUA
dAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQARgBpAGwAZQAoACcAaAB0AHQ
AcAA6AC8ALwBsAG8AYwBhAGwAaABvAHMAdAAvAHUAcABkAGEAdABlAF8AcAByAG8AZwByAGEAbQAuAG
UAeABlACcALAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnACkAOwAgAFMAdABhAHIAdAAtAFAAcgBvA
GMAZQBzAHMAIAAnAHUAcABkAGEAdABlAHIALgBlAHgAZQAnAA==
+ CategoryInfo : ParserError: (-:String) [], ParentContainsErrorR
ecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator
Because my command coded fails?
Okay, new answer as the question has changed quite drastically.
Try
#Encode Command
$command = "(New-Object System.Net.WebClient).DownloadFile('http://localhost/update_program.exe','updater.exe'); Start-Process 'updater.exe'"
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
echo $encodedCommand
#Execute command
powershell.exe -EncodedCommand $encodedcommand
This should work so long as the statements in $command are correct.
Sorry, I think I misunderstood your question at first. I think you were trying to ask how to stop Powershell from executing the string you assign to $command. If so then try the following code
powershell -command {
$command = [string] $null; $command += '(New-Object System.Net.WebClient).DownloadFile(';
$command += "'http://localhost/update_program.exe','updater.exe') ;
Start-Process 'updater.exe'"; $bytes = [Text.Encoding]::Unicode.GetBytes($command);
$encodedCommand = [Convert]::ToBase64String($bytes); echo $encodedCommand
}
Microsoft wanted smart processing of variables to enable greater compatibility between variables and functions. I think it got confused when parsing your command. What I tried was to break up the string assignation so that Powershell didn't assume that the string was a set of instructions. The single statement above calls Powershell, assigns a null string to $command, twice concatenates with strings which Powershell cannot confuse and then outputs $encodedCommand at the end. Is this what you were after?

Powershell write to vbscript console(cscript.exe)

I have a requirement of running powershell script in silent mode through vbscript(cscript.exe).
Basic steps for script are as follow.
vbscript
WScript.StdOut.WriteLine "Welcome..."
WScript.StdOut.WriteLine "First Step..."
WScript.Sleep Int(2000)
Set objShell = CreateObject("Wscript.Shell"): objShell.Run "powershell -nologo -file D:\basic\child.ps1" ,0,true
WScript.StdOut.WriteLine "Script Completed."
WScript.Sleep Int(5000)
powershell script
Write-Host "Some Text Printed"
Start-Sleep -s 2
Atthis point, I like the powershell script to write to vbscript(cscript.exe) console.
I am running vb script as follow.
cscript d:\basic\script.vbs
Is there any work around for this requirement.
As explained in the answer to the question that I linked as a possible duplicate, you can do something like this:
WScript.StdOut.WriteLine "Welcome..."
WScript.StdOut.WriteLine "First Step..."
WScript.Sleep Int(2000)
res = getCommandOutput("powershell -nologo -file D:\basic\child.ps1")
WScript.StdOut.Write res
WScript.StdOut.WriteLine "Script Completed."
WScript.Sleep Int(5000)
Function getCommandOutput(theCommand)
Dim objShell, objCmdExec
Set objShell = CreateObject("WScript.Shell")
Set objCmdExec = objshell.exec(thecommand)
getCommandOutput = objCmdExec.StdOut.ReadAll
end Function

Run Executable from Powershell script with parameters

So I have a powershell script that is supposed to run an executable with an argument to pass to set which method I want to run, and I need to pass a parameter, which is a directory to a config file. So this is what I have
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList /genmsi/f $MySourceDirectory\src\Deployment\Installations.xml
/f is the shortname and file is the long name for my attribute... I get an error in powershell telling me that a positional parameter cannot be found for /f or /file.
Any thoughts?
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
I was able to get this to work by using the Invoke-Expression cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
Just adding an example that worked fine for me:
$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg