VBScript MapNetworkDrive Error Handling - vbscript

I am attempting to write a small script in VBScript just purely for my home use, which is run prior to a scheduled backup in Macrium Reflect.
I am stuck on one seemingly small issue and that is error handling when the Network Drive is physically disconnected, i.e. the cable is not attached.
At the moment the script check to see if the Drive is already attached, if the drive is not attached then a message is displayed telling the user to connect the cable and press YES.
Now, all things being well the user would have connected the cable as asked and then pressed the YES button but I want to catch the times when YES was pressed before attaching the drive's cable.
Within the code there's an 'On Error Resume Next' which masks this eventuality, so I comment out this line & indeed I get an Error 'The Network Path Was Not Found' on line 40:
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
I want to use this caught error to display an alert to the user that the drive has not yet been connected, please connect and retry & KEEP RETRYING until the drive is actually connected.
My problem is I cannot seem to find where to add any error handling code to display this message.
Here's my code:
Option Explicit
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile, strName, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set CheckDrive = objNetwork.EnumNetworkDrives()
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters
' with strDriveLetter
On Error Resume Next
AlreadyConnected = False
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) =strDriveLetter _
Then AlreadyConnected = True
Next
If AlreadyConnected = False Then
Dim result
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." & vbNewLine & vbNewLine & "Please Connect The Drive & Press YES To Continue." & vbNewLine & vbNewLine & "If You Wish To Postpone Backup Then Press NO Now.", 4 + 32, "BACKUP DRIVE NOT CONNECTED")
If result = 7 Then
WScript.Quit
Else
Call MapDRV
End If
Sub MapDRV()
Set objNetwork = WScript.CreateObject("WScript.Network")
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
strProfile, strUser, strPassword
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
End Sub
WScript.Quit
The error handling code is something along these lines:
If Err.Number <> 0 Then
'error handling:
'ALERT USER HERE
Err.Clear
End If
Any help would be appreciated

Err Object (VBScript) reference does not give useful guide. You need to trap an error or success separate for every run-time error prone action.
Common rule (best practice): keep error handling disabled via On Error GoTo 0 and enable it only for suspected actions.
For instance, there could me more than one reason why MapNetworkDrive method could fail (server off-line, user blocked, wrong/changed password etc.):
Sub MapDRV
Dim errResult
Set objNetwork = WScript.CreateObject("WScript.Network")
errResult = ""
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
End If
End Sub
The whole script then could look as follows:
Option Explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile , strName _
, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters with strDriveLetter
Dim result, toShare
AlreadyConnected = False
Do While AlreadyConnected = False
strResult = strResult & vbNewLine & "--- new check"
AlreadyConnected = False
Set CheckDrive = objNetwork.EnumNetworkDrives()
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) = strDriveLetter Then
AlreadyConnected = True
toShare = CheckDrive.Item(intDrive + 1)
End If
strResult = strResult & vbNewLine & CheckDrive.Item(intDrive)
strResult = strResult & vbTab & CheckDrive.Item(intDrive + 1)
Next
If AlreadyConnected Then Exit Do
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." _
& vbNewLine & vbNewLine & "If you wish to ..." _
& vbNewLine & vbTab & "... postpone backup then press ABORT." _
& vbNewLine & vbTab & "... backup to " & strRemotePath & " then press RETRY." _
& vbNewLine & "Otherwise, please connect the drive & press IGNORE to continue." _
, vbAbortRetryIgnore + vbQuestion, "BACKUP DRIVE NOT CONNECTED")
Select Case result
Case vbAbort
Call scriptQuit
Case vbRetry
Call MapDRV
Case Else
' The Case Else clause is not required
End Select
Loop
strResult = strResult & vbNewLine & "copy here to " & toShare
Sub MapDRV
' no need to redefine: WshNetwork Object is already defined
' Set objNetwork = WScript.CreateObject("WScript.Network")
Dim errResult
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
strResult = strResult & vbNewLine & vbNewLine & errResult
End If
End Sub
Call scriptQuit
Sub scriptQuit
Wscript.Echo strResult
Wscript.Quit
End Sub
Please note that strResult variable is there merely for debugging purposes to see next output:
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
-2147024843 0x80070035 WSHNetwork.MapNetworkDrive
The network path was not found.
--- new check
Y: \\S-PC\VB_scripts_help
--- new check
Y: \\S-PC\VB_scripts_help
X: \\S-PC\test
copy here to \\S-PC\test
==>
Above output corresponds to next actions:
run script
1st --- new check found Y: mapped disk; then invoked Retry action failed (network path was not found);
2nd --- new check found Y: mapped disk again; then mapped disk X: manually and then invoked Ignore action;
3rd --- new check found Y: and X: mapped disks;
Do While loop exited and script continues to next action.
For completeness, following output shows invoked Abort action:
==> net use x: /delete
x: was deleted successfully.
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
==>

Related

(Legacy) MFCOM VBScript gets Invalid Procedure Call

I can list all published apps just fine, that works, but when trying to get the root applications folder I get an invalid procedure call. Does anyone know what I'm doing wrong here?
Dim theFarm,rootAppFolder
Set oWSHShell = CreateObject("Wscript.Shell")
Set oWSHNetwork = CreateObject("WScript.Network")
Set oWSHProcEnv = oWSHSHELL.Environment("PROCESS")
'Create MetaFrameFarm object
Set theFarm = CreateObject("MetaFrameCOM.MetaFrameFarm")
if Err.Number <> 0 Then
WScript.Echo "Can't create MetaFrameFarm object"
WScript.Echo "(" & Err.Number & ") " & Err.Description
WScript.Echo ""
WScript.Quit Err.Number
End if
'Initialize the farm object.
theFarm.Initialize 1
If Err.Number <> 0 Then
WScript.Echo "Can't Initialize MetaFrameFarm object"
WScript.Echo "(" & Err.Number & ") " & Err.Description
WScript.Echo ""
WScript.Quit Err.Number
End if
Set rootAppFolder = theFarm.GetRootFolder(MetaFrameAppFolder) 'error on this line here
Set appFolder = rootAppFolder.GetSubFolder("A_USA")
Set folder = appFolder.AppFolder
For each app in folder.Applications
app.LoadData(0)
WScript.Echo app.AppName
Next
Use Option Explicit to avoid blunders like an un-initialized MetaFrameAppFolder.

mapdrives script use username and password

I am trying to use a VBScript to map network drives. The script is working just fine, except when I am trying to modified it in order to use different credentials (username and password).
Option Explicit
Dim WSHNetwork, strMsg, sUser, sPass
sUser = "user12"
sPass = "testpassword"
Set WSHNetwork = WScript.CreateObject( "WScript.Network")
Call Unmap
Call TryMapDrive("N", "\\192.168.0.10\Music")
Call TryMapDrive("M", "\\192.168.0.10\Movies")
Call TryMapDrive("P", "\\192.168.0.10\Pictures")
Call TryMapDrive("W", "\\192.168.0.10\Work")
Call TryMapDrive("S", "\\192.168.0.10\Store")
strMsg = ShowNetwork() + vbCrLf + vbCrLf + EnumNetworkDrives()
MsgBox strMsg, vbInformation + vbOKOnly, "Network Properties"
Function TryMapDrive(cDrive, strShare, sUser, sPass)
On Error Resume Next
WSHNetwork.MapNetworkDrive cDrive & ":", strShare, sUser, sPass
TryMapDrive = Err.Number = 0
End Function
Function ShowNetwork
Dim strMsg
strMsg = "UserName" & Chr(9) & "= " & WSHNetwork.UserName & vbCrLf & _
"ComputerName" & Chr(9) & "= " & WSHNetwork.ComputerName
ShowNetwork = strMsg
End Function
Function EnumNetworkDrives
Dim colDrives, strMsg, i
Set colDrives = WSHNetwork.EnumNetworkDrives
strMsg = "Current network drive connections: " & vbCrLf
For i = 0 To colDrives.Count - 1 Step 2
strMsg = strMsg & vbCRLF & colDrives(i) & Chr(9) & colDrives(i+1)
Next
EnumNetworkDrives = strMsg
End Function
Function Unmap
On Error Resume Next
Dim objNetwork, colDrives, i
Set objNetwork = CreateObject("WScript.Network")
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 To colDrives.Count -1 Step 2
objNetwork.RemoveNetworkDrive colDrives.Item(i)
Next
End Function
When I am trying to start it with sPass and sUser it fails with the message below. Without trying different credentials, the script is working fine.

create folder(trusted), copy of MDE and shortcut

I have put together a script that I think will work, but the only code I know is some VBA. Never tried to create a vbscript before, so my apologies if some errors are obvious, but pointers and corrections would be appreciated.
I am hoping I can give users in my company a link to this script and have them run it. It will create a folder on their C Drive, make it a trusted location, copy a database frontend from the server into it and create a shortcut on their desktop linking to the new file. (I'm hoping the file will auto-update when a new version is made - I think that bit works though).
The code comes from various sources, including my own addled mind but would I need to download Visual Studio to test this? Slightly concerned as it includes creating a registry key and I don't know how to stop the code if it all goes horribly wrong. I don't even know how to break a loop (although I think I read somewhere you need to hit Esc twice). Any tips on how to signify which sub is the main one to run on start would be good too.
EDIT : Code has been amended to my end result incase it is of use to others. Please use with caution. The 'update' vbs deletes the folder created on the local drive.
'FrontEnd Setup
call CreateTrustedFolder
'Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS = &H80000003
'Const HKEY_CURRENT_CONFIG = &H80000005
Dim lclFolder
Dim blnUpdate
Sub CreateTrustedFolder()
On error resume next
Call RunAdmin
Call FolderFileShortcut
Call CreateReg
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Run as Administrator
Sub RunAdmin()
On error resume next
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Check if folder exists, add file and desktop shortcut
Sub FolderFileShortcut()
On error resume next
Dim oWS
Dim FSO
Dim svrFolder
Dim myShortcut
Dim strLocalDB
Dim strServerDB
Dim strUpdate
Dim strIcon
Dim objFile
Dim counter
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
If (FSO.FolderExists(lclFolder)) Then
oWS.run "icacls """ & lclFolder & """ /reset /grant:r Users:(W) /t" '/T required for existing folders
FSO.DeleteFolder lclFolder
blnUpdate = True
end if
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Installation Failed"
WScript.Quit
End If
For Each objFile in FSO.Getfolder(svrFolder).Files
if LCase(FSO.GetExtensionName(objFile.name)) = LCase("mde") then
counter = counter + 1
strServerDB = FSO.GetFileName(objFile)
end if
Next
If strServerDB = "" or counter <> 1 then
msgbox "Unable to locate the Front End" & strServerDB & "-" & counter, vbCritical, "Installation Failed"
wScript.Quit
end if
strLocalDB = "Co Database.mde"
strUpdate = "DB_UpdateCheck.vbs"
strIcon = "Frontend Update.ico"
FSO.CreateFolder(lclFolder)
oWS.run "icacls """ & lclFolder & """ /grant Users:(OI)(CI)F /t" '/T required for existing folders
FSO.CopyFile svrFolder & "\" & strUpdate, lclFolder & "\" & strUpdate, True
FSO.CopyFile svrFolder & "\" & strServerDB, lclFolder & "\" & strLocalDB, True
FSO.CopyFile svrFolder & "\" & strIcon, lclFolder & "\" & strIcon, True
strDesktop = oWS.SpecialFolders("Desktop")
set myShortcut = oWS.CreateShortcut(strDesktop + "\New Database.lnk")
myShortcut.TargetPath = lclFolder & "\" & strUpdate
myShortcut.WindowStyle = 1
myShortcut.IconLocation = lclFolder & "\" & strIcon
myShortcut.WorkingDirectory = strDesktop
myShortcut.Save
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
Sub CreateReg()
On error resume next
Dim objRegistry 'registry object
Dim strDescription 'Description of the Trusted Location
Dim strParentKey 'Registry location of Application
Dim strNewKey 'strParentKey and myFolder
Dim oWS 'WSH shell object
strDescription = "DB Folder"
strParentKey = "Software\Microsoft\Office\15.0\Access\Security\Trusted Locations"
strNewKey = strParentKey & "\" & strDescription & "\"
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
'objRegistry.GetStringValue HKEY_CURRENT_USER, strParentKey & "\" & strDescription
If Not objRegistry.EnumKey(HKEY_CURRENT_USER, strNewKey) = 0 then '0=true
objRegistry.CreateKey HKEY_CURRENT_USER, strNewKey
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Path", lclFolder
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Description", strDescription
End if
If not blnUpdate = True then
msgbox "The Database is now available from your desktop", vbInformation, "Setup Complete"
Else
msgbox "The update is now complete."
End if
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
There is also a separate Update vbs which is what runs when the link is clicked. This checks to see if the 'created date' of the database on the server is newer than that on the local drive. The new DB name MUST NOT be the same as the one it is replacing. It might run a little fast, but this is as far as I have taken this.
Call CheckForUpdate
Sub CheckForUpdate()
On Error Resume Next
Dim FSO
Dim oWS
Dim svrFolder
Dim lclFolder
Dim svrFail
Dim strLocalDB
Dim strServerDB
Dim lclDate
Dim svrDate
Dim strFileName
Dim intDBcount
Dim fCheck
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
strLocalDB = "Co Database.mde"
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Update Check Failed"
svrFail = True
End If
If Not svrFail = True Then
For Each fCheck in FSO.GetFolder(svrFolder).Files
If Ucase(Right(fCheck.Name, 3)) = "MDE" Then
intDBcount = intDBcount + 1
strServerDB = fCheck.name
End If
Next
If Not intDBcount = 1 Then
MsgBox "Please inform the Administrator that there is a problem with the Automated Update System.", _
vbCritical, "Update Failed (" & intDBcount & ")"
svrFail = True 'not quit - need to see if old version available
End If
End If
If Not (FSO.FolderExists(lclFolder)) Then
If svrFail = True Then 'If no lcl folder or server
If Not intDBcount = 1 then WScript.Quit
msgbox "You are unable to use the Database." & vbcrlf & _
"Please try again when you have access to the Location Server.", _
vbcritical, "Database Not Installed"
WScript.Quit
Else 'If no lclfolder, get it from svr
'Do normal initial install
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True
WScript.Quit
End If
Else
If svrFail = True Then 'If lcl folder, but no svr
'open db
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else 'If lcl folder and svr access, check for update.
lclDate = fso.getfile(lclFolder & "\" & strLocalDB).DateCreated
svrDate = fso.getfile(svrFolder & "\" & strServerDB).DateCreated
If lclDate < svrDate Then 'Update available
intMsg = MsgBox("An update is available - Do you wish to update now?", vbQuestion + vbYesNo, "Update Found")
If intMsg = vbYes Then
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True ',1,true should pause the code until install closes
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
End If
End If
If err Then
MsgBox "The following error has occurred " & Err & " " & Err.Description
Exit Sub
End If
End Sub

Update registry using VBS

I'm trying to update the legal caption on our PCs using a VBScript. So far, I've been able to read values but I can't seem to get it to write any values. I don't get an error when I run the script, it just doesn't change anything. It's the first time I'm doing this and I have limited experience; any insight would be appreciated:
Dim objShell
Dim strMessage, strWelcome, strWinLogon
' Set the string values
strWelcome = "legalnoticecaption"
strMessage = "did this work"
strWinLogon = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
' Create the Shell object
Set wshShell = CreateObject("WScript.Shell")
'Display string Values
Wscript.Echo "key to update: " & strWelcome
Wscript.Echo "key value to enter: " & strMessage
Wscript.Echo "Existing key value: " & wshShell.RegRead(strWinLogon & strWelcome)
' the crucial command in this script - rewrite the registry
wshShell.RegWrite strWinLogon & strWelcome, strMessage, "REG_SZ"
' Did it work?
Wscript.Echo "new key value: " & wshShell.RegRead(strWinLogon & strWelcome)
set wshShell = Nothing
NOTE: These are testing values at the moment.
Your script seems to be bug-less. However, launched by cscript 28416995.vbs returns next error (where 22 = WshShell.RegWrite line):
28416995.vbs(22, 1) WshShell.RegWrite: Invalid root in registry key "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\legalnoticecaption".
It's not invalid root, it's something like access denied rather because writing to HKLM requires elevated privileges (or run as administrator).
Note:
You should change LegalNoticeText value together with LegalNoticeCaption one.
Under the HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\ registry key there both values reside as well. For this case (if a computer is not connected to a domain or with group policy disabled) should work next script.
Run as administrator:
option explicit
On Error Goto 0
Dim wshShell
Dim strResult, strMessage, strWelcome, strWinLogon, strWinLog_2, strWinLTxt
strResult=Wscript.ScriptName
' Set the string values
strWinLTxt = "legalnoticetext"
strWelcome = "legalnoticecaption"
strMessage = "did this work"
strWinLogon = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\"
strWinLog_2 = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
' Create the Shell object
Set wshShell = CreateObject("WScript.Shell")
'Display string Values
' continue execution if requested registry values not present
On Error Resume Next
strResult = strResult & vbNewLine & "Existing Caption Policies: " _
& wshShell.RegRead(strWinLog_2 & strWelcome)
strResult = strResult & vbNewLine & "Existing Text Policies: " _
& wshShell.RegRead(strWinLog_2 & strWinLTxt)
On Error Goto 0
strResult = strResult & vbNewLine & "Existing Caption Winlogon: " _
& wshShell.RegRead(strWinLogon & strWelcome)
strResult = strResult & vbNewLine & "Existing Text Winlogon: " _
& wshShell.RegRead(strWinLogon & strWinLTxt)
strResult = strResult & vbNewLine
strResult = strResult & vbNewLine & "key to update: " & strWelcome
strResult = strResult & vbNewLine & "key value to enter: " & strMessage
' the crucial command in this script - rewrite the registry
wshShell.RegWrite strWinLogon & strWelcome, strMessage, "REG_SZ"
wshShell.RegWrite strWinLogon & strWinLTxt, UCase( strMessage), "REG_SZ"
' Did it work?
strResult = strResult & vbNewLine
strResult = strResult & vbNewLine _
& "new key Capt. value: " & wshShell.RegRead(strWinLogon & strWelcome)
strResult = strResult & vbNewLine _
& "new key Text value: " & wshShell.RegRead(strWinLogon & strWinLTxt)
Wscript.Echo strResult
set wshShell = Nothing
For me your code run perfect.
For other user that want details over this i recommend this site: http://ss64.com/vb/regread.html and ss64.com/vb/regwrite.html
Both links detail exactly the procedure that you create.
Make sure to add this:
Function RunAsAdmin()
If WScript.Arguments.length = 0 Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" & " RunAsAdministrator",,"runas", 1
WScript.Quit
End If
End Function
It will run as Admin and if it doesnt work then your key is incorrect.

Running command on remote machine using WMI

I am trying to run following VB Script to run command on remote machine. I want this script to wait until command is executed completely.
Here is my code:
Function RemoteExecute(strServer, strUser, strPassword, strCommand,pro)
Dim objLocator , objWMIService
wbemImpersonationLevelImpersonate = 3
wbemAuthenticationLevelPktPrivacy = 6
RemoteExecute = -1
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
On Error Resume Next
Set objWMIService = objLocator.ConnectServer(strServer,"root\cimv2", strUser,strPassword)
objWMIService.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
objWMIService.Security_.AuthenticationLevel = wbemAuthenticationLevelPktPrivacy
If Err.Number <> 0 Then
WScript.Echo "Failed to connect to " &strServer, "Error # " & CStr(Err.Number) & " " & Err.Description & vbcrlf & _
"Please check if " & strServer & " is pingable from this client & credentials are correct"
Err.Clear
On Error GoTo 0
RemoteExecute = -1
Set objWMIService = nothing
Set objLocator = nothing
Exit function
end if
' Configure the process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL
Set Process = objWMIService.Get("Win32_Process")
'Process.Create Syntax: '
' uint32 Create(
'[in] string CommandLine,
'[in] string CurrentDirectory,
'[in] Win32_ProcessStartup ProcessStartupInformation,
'[out] uint32 ProcessId
');
'Return code Description
'0 Successful Completion
'2 Access Denied
'3 Insufficient Privilege
'8 Unknown failure
'9 Path Not Found
'21 Invalid Parameter
intReturn = Process.Create(strCommand,NULL, objConfig, intProcessID)
If intReturn <> 0 Then
Wscript.Echo "Process could not be created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Return value: " & intReturn
Wscript.Quit
Else
Wscript.Echo "Process created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Process ID: " & intProcessID
RemoteExecute = intProcessID
End If
' Set objWMIService = GetObject("winmgmts:\\" & strServer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery_("SELECT *" +" FROM __InstanceDeletionEvent " +"WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' " )
Do
Set objProcess = colMonitoredProcesses.NextEvent
Wscript.Echo objProcess.TargetInstance.Name
Wscript.Echo objProcess.TargetInstance.ExecutablePath
Wscript.Echo "1"
Wscript.Echo "proc:" & objProcess.TargetInstance.ProcessID
Wscript.Echo "int:" & intProcessID
If objProcess.TargetInstance.ProcessID = intProcessID Then
Wscript.Echo "I will end the monitoring of the process "
Wscript.Echo pro & objProcess.TargetInstance.Name
Exit Do
end If
Loop
Set objWMIService = nothing
Set objLocator = nothing
End Function
strServer = WScript.Arguments.Item(0)
strUser = WScript.Arguments.Item(1)
strPassword = WScript.Arguments.Item(2)
strCommand = WScript.Arguments.Item(3)
pro = WScript.Arguments.Item(4)
Call RemoteExecute(strServer, strUser, strPassword, strCommand,pro)
But problem I am facing is that, script run the process in background but not waiting for it.
Another point that I do not understand is, when try to echo following:
Wscript.Echo objProcess.TargetInstance.Name
Wscript.Echo objProcess.TargetInstance.ExecutablePath
Wscript.Echo "proc:" & objProcess.TargetInstance.ProcessID
it does no echo anything, whereas following are properly echoed with a nice pop up
Wscript.Echo "1"
Wscript.Echo "int:" & intProcessID
Can someone please resolve my problem, may be this problem is naive for someone, sorry I am naive here.

Resources