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
Related
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.
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
}
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
The goal is to automate the execution of 3 files:
A batch file that runs a selenium webdriver automated test suite.
Another batch file that generates a reports for the tests run in step 1.
A PowerShell script that attaches the reports and sends an email.
How can I automate the execution of these 3 files so that upon running a command or executing a file, all 3 are executed?
This is how my PowerShell looks like:
$Username = "";
$Password = "";
function Send-ToEmail([string]$email, [string]$attachmentpath) {
$message = New-Object Net.Mail.MailMessage;
$message.From = "c#c.com";
$message.To.Add($email);
$message.Subject = "abc";
$message.Body = "abc";
$attachment1 = New-Object Net.Mail.Attachment($attachmentpath);
$message.Attachments.Add($attachment1);
$smtp = New-Object Net.Mail.SmtpClient("build3", "25");
$smtp.EnableSSL = $false;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.Send($message);
Write-Host $smtp.EnableSSL;
Write-Host "Mail Sent";
}
Send-ToEmail -email "a#a.com" -attachmentpath "C:\file1";
Send-ToEmail -email "b#b.com" -attachmentpath "C:\file1";
This is what the first batch file looks like:
FOR /F "TOKENS=2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=2,3,4 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C
SET todaysdate=%yyyy%%mm%%dd%
start /d "nunitPATH" nunit3-console.exe "seleniumtestsuite dll PATH" --where:cat==SignUp --result="xmlreportPATH"
This is what the second batch file looks like:
start /d "exeFilePATH" ReportUnit.exe "folderPATH"
Simply write a batch script that runs
call script1.bat
call script2.bat
D:\path\to\powershell.exe -File script3.ps1
If you need async:
start script1.bat
start script2.bat
start "" "D:\path\to\powershell.exe" "-File" "script3.ps1"
Note the pair of double quotes before powershell.exe path.
Note that this assumes your device has at least powershell v2
However, this question is a duplicate of here
This VBScript runs a few PowerShell scripts. I put the invocation of notepad.exe there to make sure it ran as an admin.
My PowerShell scripts open consoles but then they close immediately.
I would like to have them stay open.
What is wrong?
Here is my VBScript:
RunAsAdmin()
Set shell = WScript.CreateObject("WScript.shell")
shell.Run("powershell.exe -noexit -executionpolicy bypass -file .\Source\RemoveWindows10Apps-2.0.ps1"), 1 , True
Set shell = WScript.CreateObject("WScript.shell")
shell.Run("powershell.exe -noexit -executionpolicy bypass -file .\Source\ChangeWin10StartLayout.ps1"), 1 , True
Set shell = WScript.CreateObject("WScript.shell")
shell.Run("powershell.exe -noexit -executionpolicy bypass -file .\Source\NewFolder.ps1"), 1 , True
Set shell = WScript.CreateObject("WScript.shell")
shell.Run("notepad.exe"), 1 , True
Function RunAsAdmin()
Dim objAPP
If WScript.Arguments.length = 0 Then
Set objAPP = CreateObject("Shell.Application")
objAPP.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" & " RunAsAdministrator",,"runas", 1
WScript.Quit
End If
End Function
I guess it is because you use relative paths so when your script will call itself as admin your current directory will change to ...\WINDOWS\system32.
Try it with building absolute paths and pass them to PowerShell like so
RunAsAdmin()
strScriptPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strScriptPath )
strScriptFolder = objFSO.GetParentFolderName(objFile)
Set shell = WScript.CreateObject("WScript.shell")
shell.Run("powershell.exe -noexit -executionpolicy bypass -file " & strScriptFolder & "\Source\RemoveWindows10Apps-2.0.ps1"), 1 , True
...