Monday, June 16, 2008

Start a process remotely

I'm back with another script fresh from the oven.  This time we're going to create a function that will connect to a machine and create a process.  Before you say "why would I want to create a process, we've got too many processes around here", think of it like this:  Say you have a computer somewhere that you want to run a command like ipconfig /flushdns on.  Well, ipconfig doesn't have a way of doing it remotely.  Now you are stuck with writing out some code to do it via WMI.   While that's great, sometimes it's just easier to type in "ipconfig /flushdns" and you wish you could just tell the dang computer to run it.

Well you can and it turns out, it's pretty simple too.   First, we'll connect to the computer.  Next, we'll create a new process (in this case, ipconfig.exe).  Then we'll pass some switches to it ("/flushdns").  Lastly, we'll run the command and capture the return code to try and determine if the process started successfully.

Before you plop this code into your script, here's a tip.  The function returns a boolean value based on the return code from the OS.  I did my best job trying to interpret the codes into a True/False return code but you may need to modify it for your script.  Also, the function stores the return type (string) so you can get a nice status of the return code.  To use this, declare startExeStatus globally (in the main part of your script).  Then call the function.  It will set the variable to the status.

So here's the code:

Function startExe(sstrComputer,sstrEXE)
'Starts a process on a machine
'Input: sstrComputer = machine name (use "." for local)
'Input: sstrExe = Exe or command to execute (can pass full command line)
'Output: boolean
'Optional: Declare startExeStatus as a global variable to get status text
 
    
    startExe = False 
    Set sobjWMIService = GetObject("winmgmts:\\" & sstrComputer & "\root\cimv2:Win32_Process")
    
    sintReturn = sobjWMIService.Create(sstrEXE, null, null, sintProcessID)
    
    Select Case sintReturn
 
        Case 0 'Successful Completion
            startExe = True
            startExeStatus = "Successful Completion"
            
        Case 2 'Access Denied
            startExe = False
            startExeStatus = "Access Denied"
            
        Case 3 'Insufficient Privilege
            startExe = False
            startExeStatus = "Insufficient Privilege"
            
        Case 8 'Unknown Failure
            startExe = False
            startExeStatus = "Unknown Failure"
            
            
        Case 9 'Path not found
            startExe = False
            startExeStatus = "Path not found"
            
        Case 21 'Invalid Parameter
            startExe = False
            startExeStatus = "Invalid Parameter"
            
        Case Else 
            startExe = False
            startExeStatus = "Error code " & sintReturn & " not found"
            
    End Select 
 
 
End Function 

 

Here's the background on why I created this function.  We have a need to create a scheduled task on a lot (and I mean a LOT) of machines.  We were using schtasks.exe and for the most part it worked fine.  However, one day we found several hundreds of machines that weren't scheduling the tasks.  After some investigation, the machines were returning back as not being NT or higher even though they were on XP SP2.  The need to create the task was great so we worked around it.

I found that creating the task locally worked like a charm.  So the function was born.  It's been used for all kinds of stuff since like ipconfig /flushdns.  Use wisely.  :)

As always, these scripts are free to use and at your own caution.  So don't hold me responsible for any crashes or other bad things you do with it.

-Corey

Wednesday, May 21, 2008

RemoteService Function

Slacker.  Go ahead, say it. I know your thinking it.  Work has been busy but that doesn't mean I'm slacking off on coding.  Oh no, I'm hard at work writing new functions and subs.  I finished one recently when I needed to stop and start a service on a remote machine.  And as usual, I couldn't just make a sub that only stopped and started a service.  I had to add in other abilities like Pause, Resume, and Restart.  Oh yeah, now we're talking.

But that's not all.  I started to think, what else would I want to do with a service?  How about changing it's startup type to Automatic, Manual, or Disabled?  That's something we network administrators need to do from time to time.  So I added that in too.

I wrapped all the code up in a nifty little sub (sorry, no shiny paper and bow).  To use it, simply pass the computer name, service name, and the action you want to complete and presto!  The service will be changed.

chrip chrip chrip..  What's that?  The little birdy on my shoulder said "what about errors?".  Good point.  What if we want to capture the return status of the action?  For example, what if I try to start a service that is already started?  It turns out that we can capture the return code.  The code is a user un-friendly integer so run it through a select case and set a boolean variable as true/false as well as setting some status text. So now that we have that, how do we pass two variables back?  You can't pass it back in a single function.  So here's what I did.

To get the return code and status, declare these two variables in the main part of the script: blnServiceStatus and strServiceStatus.

When the action on the service completes, the return code is filtered and these two variables are set.  All you need to do is declare them globally and now you've got the status!  One special note on the blnServiceStatus results, I tried my best to interpret the return code as a true or false as representative of the success of the action.  You may need to tweak these for your desired results.

All this talk and no action.  Let's see some code!

Sub remoteService(sstrComputer,sstrService,sstrAction)
'This accepts a computer name, service name, and action to complete on the service.
'Input: sstrComputer = Machine to perform action on.  Use "." for local
'Input: sstrService = Name of the service
'Input: sstrAction = See options below
'        "Start" = Start the service
'        "Stop" = Stop the service
'        "Restart" = Restart the service
'        "Pause" = Pause the service
'        "Resume" = Resume the service
'        "Automatic" = Set the startup type to Automatic
'        "Manual" = Set the startup type to Manual
'        "Disabled" = Set the startup type to Disabled
 
'To get the status codes:
'1.  Declare strServiceStatus and blnServiceStatus globally (Main part of the script)
'2.  Call this sub as usual.
'3.  blnServiceStatus will be set to True if successfull.  
'4.  strServiceStatus will be set to the status of the action
 
 
 
On Error Resume Next 
    Set sobjWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & sstrComputer & "\root\cimv2")
    
    Set scolServiceList = sobjWMIService.ExecQuery("Select * from Win32_Service where Name='" & sstrService &"'")
    'Set colServiceList = objWMIService.ExecQuery("Select * from Win32_Service")
 
    For Each sobjService in scolServiceList
        'WScript.Echo sobjService.Name
        
        sstrAction = UCase(sstrAction)
        Select Case sstrAction
        
            Case "START"
                serrReturn = sobjService.StartService()
           
            Case "STOP"
                serrReturn = sobjService.StopService()
                
            Case "RESTART"
                serrReturn = sobjService.StopService()
                serrReturn = sobjService.StartService()
                
            Case "PAUSE"
                serrReturn = sobjService.PauseService()
                
            Case "RESUME"
                serrReturn = sobjService.ResumeService()
                
            Case "AUTOMATIC"
                serrReturn = sobjService.ChangeStartMode("Automatic")
            
            Case "MANUAL"
                serrReturn = sobjService.ChangeStartMode("Manual")
            
            Case "DISABLED"
                serrReturn = sobjService.ChangeStartMode("Disabled")
        
        End Select
        
        'WScript.Echo serrReturn
        
        Select Case serrReturn
        
        
            Case 0  'Success
                blnServiceStatus = True
                strServiceStatus = "Success"
                
            Case 1    'Not Supported
                blnServiceStatus = False
                strServiceStatus = "Not Supported"
            
            Case 2    'Access Denied
                blnServiceStatus = False
                strServiceStatus = "Access Denied"
            
            Case 3    'Dependent Services Running
                blnServiceStatus = True
                strServiceStatus = "Dependent Services Running"
 
            Case 4    'Invalid Service Control
                blnServiceStatus = False
                strServiceStatus = "Invalid Service Control"
 
            Case 5    'Service Cannot Accept Control
                blnServiceStatus = False
                strServiceStatus = "Service Cannot Accept Control"
 
            Case 6    'Service Not Active
                blnServiceStatus = False
                strServiceStatus = "Service Not Active"
 
            Case 7    'Service Request Timeout
                blnServiceStatus = False
                strServiceStatus = "Service Request Timeout"
 
            Case 8    'Unknown Failure
                blnServiceStatus = False
                strServiceStatus = "Unknown Failure"
 
            Case 9    'Path Not Found
                blnServiceStatus = False
                strServiceStatus = "Path Not Found"
 
            Case 10    'Service Already Running
                blnServiceStatus = True
                strServiceStatus = "Service Already Running"
 
            Case 11    'Service Database Locked
                blnServiceStatus = False
                strServiceStatus = "Service Database Locked"
 
            Case 12    'Service Dependency Deleted
                blnServiceStatus = True
                strServiceStatus = "Service Dependency Deleted"
 
            Case 13    'Service Dependency Failure
                blnServiceStatus = False
                strServiceStatus = "Service Dependency Failure"
 
            Case 14    'Service Disabled
                blnServiceStatus = True
                strServiceStatus = "Service Disabled"
 
            Case 15    'Service Logon Failure
                blnServiceStatus = False
                strServiceStatus = "Service Logon Failure"
 
            Case 16    'Service Marked For Deletion
                blnServiceStatus = True
                strServiceStatus = "Service Marked For Deletion"
 
            Case 17    'Service No Thread
                blnServiceStatus = False
                strServiceStatus = "Service No Thread"
 
            Case 18    'Status Circular Dependency
                blnServiceStatus = False
                strServiceStatus = "Circular Dependency"
 
            Case 19    'Status Duplicate Name
                blnServiceStatus = False
                strServiceStatus = "Duplicate Name"
 
            Case 20    'Status Invalid Name
                blnServiceStatus = False
                strServiceStatus = "Invalid Name"
 
            Case 21    'Status Invalid Parameter
                blnServiceStatus = False
                strServiceStatus = "Invalid Paramenter"
 
            Case 22    'Status Invalid Service Account
                blnServiceStatus = False
                strServiceStatus = "Invalid Service Account"
 
            Case 23    'Status Service Exists
                blnServiceStatus = True
                strServiceStatus = "Service Exists"
 
            Case 24    'Service Already Paused  
                blnServiceStatus = True
                strServiceStatus = "Already Paused"
        
        
        End Select
        
    Next
    
 
End Sub 

And there you have it.  A nice and robust sub for handling services.  Remember, you can use this in a local script too.  Just use "." as the computer name.  :)

 

Happy coding!

-Corey

Thursday, April 17, 2008

Create a new link in Favorites

Well, it's been a while since I've been able to post a new script.  Guess I've been too busy using my skillz to pay the billz as they say...  So today I'm posting a new script or rather, a snippet you can use in your own scripts.  This comes directly from my library of functions and is used frequently in enterprise logon scripts.

 

As a system administrator, you may find it necessary to create a script to add a link to a user's favorites.  There are several ways to do this including Group Policy, copying the .url or .lnk to the local computer, or vbscript.  I could put my smartz hat on and show you how it's done via group policies but this is a scripting blog.  I could also show you how to copy a shortcut file via copy, xcopy, or robocopy but that would be no fun.

 

So let's look at a script all ready, begeezus!  Fine.  There are really two things you can do.  1.  Copy a premade link using the filesystemobject.  Or, and better yet.. 2. Create a shortcut file on the fly using the Wscript.Shell object.

 

Code:

Sub CreateFavorite(sstrURL, sstrFileName, sstrFolder)
'Notes: Creates a favorite for the current logged on user.
'Input: strURL = URL to website
'Input: strFilename = file name to save (ex. technet.url)  
'Input: strFolder = folder to put the favorite in.  (pass null and it will default to the root)
 
    sstrURL = Trim(sstrURL)
    sstrFileName = Trim(sstrFileName)
    Set sobjFSO = CreateObject("Scripting.FileSystemObject")
    
    If IsNull(sstrFolder) Then
        sstrFolder = ""
    End If 
    
    If Not UCase(Right(sstrFileName,3)) = "URL" Then
        sstrFileName = sstrFileName & ".url"
    End If 
    
    Set sWshShell = CreateObject("WScript.Shell")
    sstrPath = sWshShell.SpecialFolders("Favorites")
    
    If Not sobjFSO.FolderExists(sstrPath & "\" & sstrFolder) Then
        sobjFSO.CreateFolder(sstrPath & "\" & sstrFolder)
    End If 
        
    Set sobjShortcutUrl = sWshShell.CreateShortcut(sstrPath & "\" & sstrFolder & "\" & sstrFileName)
    sobjShortcutUrl.TargetPath = sstrURL
    sobjShortcutUrl.Save 
 
End Sub 

 

To use:  Simply call CreateFavorite and pass the information.

Example:  CreateFavorite "http://vbscripter.blogspot.com", "VBScript Blog", "VBScript Stuff"

 

This will create a link called "VBScript Blog" to this website in a folder called VBScript Stuff inside Favorites.  Nifty. 

Take note that this is ran locally so you'll need to execute it via logon script or some other method like remote scripting, etc.  Enjoy!

 

Until next time (whenever that may be at this rate)!

-Corey