user3802783
user3802783

Reputation: 23

Close program opened by vbs script with same script

im looking for a simple code to add to this to exit the program

Set WshShell = WScript.CreateObject("WScript.Shell") 
WshShell.Run("powershell.exe") 
wscript.sleep 2
wshshell.AppActivate "powershell"
wscript.sleep 145
wshshell.sendkeys"ipconfig /all > C:\Users\Public\file.txt"
wshshell.sendkeys"~"
wscript.sleep 300
wscript.sleep 145
wshshell.sendkeys"cls~"

Upvotes: 2

Views: 4324

Answers (2)

Abdullah Leghari
Abdullah Leghari

Reputation: 2470

You can use WshShell.Exec("powershell.exe") instead of WshShell.Run("powershell.exe").

Set WshShell = WScript.CreateObject("WScript.Shell") 
Set app = WshShell.Exec("powershell.exe") 
wscript.sleep 2
wshshell.AppActivate "powershell"
wscript.sleep 145
wshshell.sendkeys"ipconfig /all > C:\Users\Public\file.txt"
wshshell.sendkeys"~"
wscript.sleep 300 ' **** See note below *****
wscript.sleep 145
wshshell.sendkeys"cls~"
app.Terminate

app.Terminate would close your program.

Note: app.Terminate won't wait for your tasks to complete before closing the application. With your code above it will close PowerShell even before it is fully loaded.

A quick workaround is to increase the sleep time.

wscript.sleep 300

A sleep time of 10000 is a safe guess for the powershell to load and ipconfig command to execute.

Upvotes: 1

Lews Therin
Lews Therin

Reputation: 3777

Just send the exit command to powershell:

wshshell.sendkeys"exit~"

Upvotes: 1

Related Questions