Windows Tech Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 23 February 2011

Launch IE and Wait for it to be Closed

Posted on 11:26 by Unknown
I really thought this was going to be easier than it turns out to be.  First off, the Wscript.Shell RUN() method is useless with IE when it comes to specifying Wait = True.  It ignores it.  If you make one script call another (via Wscript.Run or Execute, doesn't matter) it works, but not if you deploy the script "per-user" via SCCM, in which case, again, the Wait = True is ignored in the parent script.  So, script A launches script B, but instead of waiting for B to complete, script A just continues on while B is still working.  NOT what I want to happen.  The net result is crap and breaks the workflow entirely.  The solution is WMI and the Win32_ProcessStartup class (and a little scripting and some coffee).


The way this works is that it assumes the web page (running on a trusted intranet server) takes user input via a form and then evokes some sort of modification to the user account in Active Directory via an LDAP expression.  As an example, I'm using an account attribute called "customAttrib" and checking if it is empty (is-null or empty-string) or contains a string value (more than one character).  If the value is empty, the web form is launched and the script waits until the user closes the IE session.  It doesn't matter how many other IE windows or tabs are open.  It fetches the processID for the one it launches and watches to see when it vanishes from the process stack (using a do-while loop).  When the process is closed, the script continues and simply re-checks the attribute to see if it was modified.  The end-game being that it checks if the user successfully completed the form, or simply closed it and tried to ignore it (bad news for the user).  Enjoy!


'****************************************************************
' Filename..: IE_Wait.vbs
' Author....: skatterbrainz.blogspot.com (you know who)
' Date......: 02/23/2011
' Purpose...: launch web page and wait for it to close
'****************************************************************
' comment: check for previous attrib in AD (LDAP query)
' comment: launch ie and navigate to the web page
' comment: check AD again to see if user completed the form
' comment: if not, force a logoff
'****************************************************************


Const enableLogoff = True
Const dndc = "LDAP://DC=contoso,DC=msft"


'----------------------------------------------------------------
' comment: DO NOT MODIFY ANY CODE BELOW THIS POINT!!!
'----------------------------------------------------------------


Const ADS_SCOPE_SUBTREE = 2
Const SW_HIDE = 0
Const SW_NORMAL = 1
Const SW_SHOWMINIMIZED = 2
Const SW_SHOWMAXIMIZED = 3


Const wbemFlagForwardOnly = 32
Const wbemFlagBidirectional = 0
Const wbemFlagReturnImmediately = 16
Const wbemFlagReturnWhenComplete = 0
Const wbemQueryFlagPrototype = 2
Const wbemFlagUseAmendedQualifiers = 131072


Const osLogoff = 0
Const osForcedLogoff = 4
Const osShutdown = 1
Const osForcedShutdown = 5
Const osRestart = 2
Const osForcedRestart = 6


Const strCommand = "C:\Program Files\Internet Explorer\iexplore.exe http://intranet.contoso.msft/stuff"


Dim wshNetwork, uid, objShell, groupPriority, wmi_flags


wmi_flags = wbemFlagForwardOnly + wbemFlagReturnImmediately


Set wshNetwork = CreateObject("Wscript.Network")
Set objShell   = CreateObject("Wscript.Shell")


uid = wshNetwork.UserName
Set wshNetwork = Nothing


custVal = GetAttribute(uid, "customAttrib")


If IsNull(groupPriority) Then   
    LaunchWebForm()


    custVal = GetAttribute(uid, "customAttrib")


    If IsNull(custVal) Then
        MsgBox "Form was not filled out properly!" & _
            vbCRLF & "You will now be logged off...", vbOkOnly+vbCritical, "Web Form"
            
        If enableLogoff = True Then
            Logoff()
        End If
        
    End If
End If


Sub LaunchWebForm()
    Dim objWMIService, objStartup, objConfig, objProcess
    Dim intReturn, query, colItems, objItem, intProcessID
    Dim colMonitoredProcesses, objLatestProcess, processEnded
    
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\.\root\cimv2")


    ' comment: configure the new process as visible
    Set objStartup = objWMIService.Get("Win32_ProcessStartup")
    Set objConfig = objStartup.SpawnInstance_
    objConfig.ShowWindow = SW_NORMAL


    ' comment: create a new process (iexplore.exe)
    Set objProcess = objWMIService.Get("Win32_Process")
    intReturn = objProcess.Create(strCommand, Null, objConfig, intProcessID)


    If intReturn <> 0 Then
        'wscript.echo "fail: unable to launch process!"
        wscript.quit(1)
    End If



    'wscript.echo "info: process id is " & intProcessID


    Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2") 


    query = "SELECT ProcessId FROM Win32_Process WHERE ProcessId='" & intProcessID & "'"


    Set colItems = objWMIService.ExecQuery(query,,wmi_flags) 
    For Each objItem in colItems
        intProcessID = objItem.ProcessId
    Next
        
    If intProcessID <> "" Then
        'wscript.echo "info: waiting for process terminate..."
        
        Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
            ("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")


        Do Until processEnded = True
            Set objLatestProcess = colMonitoredProcesses.NextEvent
            If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
                processEnded = True
            End If
        Loop


        If processEnded = True Then
            'wscript.echo "info: process was terminated"
        End If
    Else
        'wscript.echo "fail: unable to obtain process id..."
    End If
End Sub


'----------------------------------------------------------------
' function: get LDAP user attribute from AD
'----------------------------------------------------------------


Function GetAttribute(uid, att)
    Dim query, objConnection, objCommand, objRecordSet, retval
    On Error Resume Next
    
    query = "SELECT " & att & " FROM '" & dndc & "' " & _
        "WHERE objectCategory='user' AND sAMAccountName='" & uid & "'"
    
    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand    = CreateObject("ADODB.Command")
    
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    
    Set objCommand.ActiveConnection = objConnection
    
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    
    objCommand.CommandText = query
    
    Set objRecordSet = objCommand.Execute
    
    objRecordSet.MoveFirst
    Do Until objRecordSet.EOF
        retval = objRecordSet.Fields(att).value    
        objRecordSet.MoveNext
    Loop
    GetAttribute = retval
End Function


'----------------------------------------------------------------
' function: force logoff from local computer
'----------------------------------------------------------------


Function Logoff()
    Logoff = -1
    wscript.Echo "Logging off..."
    On Error Resume Next
    Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\.\root\cimv2")
    Set colOs = objWMI.ExecQuery("Select * from Win32_OperatingSystem")
    If err.Number = 0 Then
        For Each objOs in colOs
            ' See: http://msdn.microsoft.com/en-us/library/aa394058(VS.85).aspx
            Logoff = objOs.Win32Shutdown(osForcedLogoff,0)
            ' WScript.Echo objOs.Name
        Next
    End If
End Function

Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in active directory, internet explorer, ldap, programming, scripting, vbscript | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Voting Time: Help Me Out?
    I need to get a better view of how I should manage this blog if I'm going to keep at it. I'd like to know how you typically discover...
  • A World Without Competition
    Try to imagine what things would be like today had there not been fierce competition in certain key parts of our world.  I’ll give you some ...
  • Book Update
    I posted some gibberish a few weeks ago about another book project.  Well, I'm getting close to wrapping it up, so I thought I'd go ...
  • Cost
    Software technology, like any technology, provides a means to solving problems.  Some big. Some small.  Some that help.  Some that hurt.  An...
  • Windows 7: Default User vs All Users
    A lot of confusion seems to occur with understanding the difference between the "Default User" profile, and the "All Users...
  • Time to Give Props
    With the ever-expanding volume and breadth of information on the Internet today, it's easy to focus on my own thoughts, experiences, ide...
  • Table of Contents (Preliminary)
    Here's the preliminary Table of Contents for my new book "The AutoCAD Network Administrator's Bible - 2013 Edition".  I...
  • The Nicest IT and IT Vendor Folks I Know
    I've ranted many times before how it's unfair to "hate" an entire company, without providing a rationale for it based on s...
  • Windows 8
    Two small, yet irritating things, that I hope Windows 8 addresses with respect to Windows 7: Being able to put the Recycle Bin in the S...
  • Stupid Assumptions
    After years of watching sci-fi TV shows, movies, etc. it's finally come to a point where even the so-called brightest of our authors and...

Categories

  • a
  • activation
  • active directory
  • advertising
  • agile
  • agility
  • amazon
  • american
  • apple
  • application virtualization
  • applications
  • art
  • articles
  • asp
  • augi
  • authors
  • autocad
  • AutoCAD Autodesk
  • autodesk
  • autolisp
  • automation
  • automotive
  • backups
  • batch
  • beer
  • beta
  • blackberry
  • blogs
  • bongloads
  • book
  • books
  • Books writing kindle amazon technology business projects
  • browsers
  • business
  • cad
  • career
  • certification
  • chrome
  • city government
  • civilization
  • cloud services
  • cmd
  • cmmi
  • comedy
  • command
  • community
  • computers
  • conferences
  • config manager
  • consultants
  • consulting
  • contracting
  • cranium drainium
  • crapware
  • culture
  • data center
  • data mining
  • databases
  • deployment
  • directx
  • DLL
  • domains
  • dumb
  • earth
  • economy
  • editor
  • education
  • election
  • elections
  • employment
  • engineering
  • entertainment
  • environment
  • error monitoring
  • events
  • exchange
  • facebook
  • family
  • firefox
  • flexnet
  • fud
  • fun
  • funny
  • games
  • gary vaynerchuk
  • gmail
  • google
  • government
  • group policy
  • hampton roads
  • health
  • history
  • holidays
  • home
  • html5
  • humor
  • hyper-v
  • iis
  • industry
  • infrastructure
  • installation
  • installshield
  • internet
  • internet explorer
  • interviews
  • jobs
  • jtbworld
  • kindle
  • kixtart
  • lab setup
  • languages
  • ldap
  • learning
  • legal
  • licensing
  • life
  • lifecycle
  • linux
  • lisp
  • logging
  • management
  • manufacturing
  • marketing
  • markets
  • mdop
  • mdt
  • medical
  • messaging
  • microsoft
  • microsoft access
  • military
  • mountains
  • movies
  • mozilla
  • music
  • nature
  • network administration
  • news
  • nook
  • nothing
  • office
  • open source
  • openoffice
  • opera
  • operating systems
  • oracle
  • osx
  • packaging
  • patches
  • people
  • photos
  • podcasts
  • policy
  • politics
  • powershell
  • predictions
  • process automation
  • products
  • programming
  • projects
  • psychology
  • publishing
  • rail
  • reading
  • registry
  • religion
  • reporting
  • reviews
  • rsat
  • rss
  • safari
  • safety
  • sales
  • satire
  • sccm
  • scheduling
  • science
  • scripting
  • search
  • security
  • servers
  • services
  • sharepoint
  • shopping
  • sms
  • social stuff
  • society
  • softgrid
  • software assurance
  • software deployment
  • software development
  • software packaging
  • sony
  • speaking
  • sports
  • sql express
  • sql server
  • statistics
  • Statistics news marketing
  • steve jobs
  • stories
  • stuff
  • stupidity
  • symantec
  • sysinternals
  • system center
  • systems architecture
  • t-sql
  • taxes
  • technet
  • technical support
  • technology
  • TED
  • ted talks
  • testing
  • textpad
  • thoughts
  • traffic
  • training
  • transportation
  • travel
  • troubleshooting
  • tutorials
  • twitter
  • ubuntu
  • unattend
  • unemployment
  • updates
  • upfront ezine
  • utilities
  • vacation
  • vba
  • vbscript
  • video
  • virginia
  • virginia beach
  • virtualization
  • visual lisp
  • vmware
  • vmware server
  • voting
  • war
  • weather
  • web
  • web browsers
  • web development
  • web sites
  • windows
  • windows 7
  • windows live
  • windows server
  • windows server 2012
  • windows8
  • winpe
  • wise
  • wmi
  • work
  • writing
  • ws08
  • wsus
  • wwa
  • x64
  • xml
  • ze frank

Blog Archive

  • ►  2013 (37)
    • ►  October (1)
    • ►  September (5)
    • ►  August (8)
    • ►  July (2)
    • ►  June (4)
    • ►  May (4)
    • ►  April (2)
    • ►  March (2)
    • ►  February (8)
    • ►  January (1)
  • ►  2012 (120)
    • ►  December (14)
    • ►  November (12)
    • ►  October (10)
    • ►  September (7)
    • ►  August (3)
    • ►  July (2)
    • ►  June (6)
    • ►  May (6)
    • ►  April (20)
    • ►  March (16)
    • ►  February (18)
    • ►  January (6)
  • ▼  2011 (343)
    • ►  December (15)
    • ►  November (23)
    • ►  October (27)
    • ►  September (35)
    • ►  August (29)
    • ►  July (17)
    • ►  June (23)
    • ►  May (20)
    • ►  April (38)
    • ►  March (61)
    • ▼  February (54)
      • MSIEXEC Error Codes
      • IBM and Watson
      • Consulting Rules
      • How to Make Better Drivers
      • Launch IE and Wait for it to be Closed
      • Another Interview, part 2
      • Upgrades and Downgrades
      • New Zealand
      • Group Policy Horrors
      • Standards Needed
      • My Eyes are Permanently Damaged
      • AutoCAD Performance Tips
      • Shitty Web Sites of The Week
      • The %ProgramFiles% Bug, Part 2 / Distrust & Uncert...
      • Microsoft: Too Early, Too Late
      • So far today...
      • Script of the Day - Open IE on Login (Just One Time)
      • Happy Friday
      • IT Jobs
      • Software Licensing
      • Mixing Gravy with Lumps
      • What Goes Up…
      • Tenuous Linking
      • Sys Admin Tips, Part 1
      • Observations
      • Grammy's Get it Right
      • What a slob I am
      • Repeat After Me: Beer is Tasty
      • Programming Ka-blamming
      • Songs I Could Do Without: Forever
      • Parse and Reparse were Sitting on a Fence
      • Happy Friday: Scripting Windows Search
      • Out of the Box and Free
      • Weekly Summary
      • LDAP / AD script stuff
      • Democracy 101
      • Stupidity
      • Food for Thought
      • Misperceptions are Often Impossible to Change
      • Right Way, and Wrong Way
      • Useful SCCM Developer Tip of the Day
      • Avoid Extremes
      • The Day After
      • Stack Overflow in a pinch
      • Attention AD Admins
      • Bugs/Annoyances: TurboTax Online
      • Windows Admin Basics: Security 101
      • Is Computer a Member of a Domain "Laptops" Group
      • Detection Deflection Reflection
      • Let's Put This Another Way
      • Top-Ranked Customer Service
      • SCCM Web Management
      • Fonts: 101
      • How to: Convert MIT Open Courseware to Kindle Reader
    • ►  January (1)
Powered by Blogger.

About Me

Unknown
View my complete profile