PowerShell Script Register-OutlookProfile.ps1

Project Objective:
Convert existing Batch logon script, Configure-Outlook.bat, to PowerShell, while doing so improve upon the proper Outlook version enumeration with a registry check.

Problem to be solved:
Current script has been written in Batch. Getting Batch logon scripts to run the same way they ran in Windows XP, on Windows Vista and Windows 7 has become a game of hit and miss. This script, in its Batch form, runs just fine. So re-writing it in PowerShell is merely for academic and consistency purposes.

Suggestions:
None.. Just re-write it and learn.

Future Versions:
The current version is not passing the variables to the environment that is launched at the end of the script. I am sure this is an error on my part. I just need to sit down and figure out what I am doing wrong.

# WARNING WORK IN PROGRESS
# This script is currently not working as it should.
# I am looking into why and debugging. It is based on a
# working batch version, its just a matter of getting it
# to work in PowerShell
# – Aaron Wurthmann

function Test-ServerOS {
    if ($OS.Caption -like "*Server*"){
        exit
    }
}

function Test-Profile {
    if ($OS.Version -gt 6.0){
        $strProfileDir="$env:USERPROFILEAppDataRoamingMicrosoftOutlook"
    }
    Else {
        $strProfileDir="$env:USERPROFILELocal SettingsApplication DataMicrosoftOutlook"
    }
    $ProfileResult=test-path $strProfileDir
    if ($ProfileResult=$true){
        exit
    }
}

function Get-Outlook {
    $regOutlook=Get-Itemproperty -path "HKLM:SoftwareMicrosoftWindowsCurrentversionApp Pathsoutlook.exe"
    $getOutlook=$regOutlook.path +'outlook.exe'
    $outlook=Get-Item $getOutlook
}

function Test-Config {
    $ConfigResult=test-path $config
    if ($ConfigResult=$false){
        exit
    }
}

$env:ExchServer="EXCHANGE.DOMAIN.EXT"
$env:OWAServer="OWA.DOMAIN.EXT"
$env:MailProfile="Outlook"
$env:ExchProfile="EXCHANGE-PROFILE.PRF"
$config="$env:logonservernetlogonmodulesexchange-profiles$env:ExchProfile"

$OS=Get-WmiObject -Class win32_OperatingSystem -namespace "rootCIMV2"
Test-ServerOS
Test-Profile
Get-Outlook
Test-Config
& $outlook /importprf $config

Batch Script Configure-Outlook.bat

Project Objective:
Lower TCO (total cost of ownership) on Outlook configurations while setting everyone’s Outlook/Exchange setup to the same uniform settings. (Use cache mode and use RPC over HTTPS)

Problem to be solved:
Lower TCO and IT man hours spent on configuring Outlook.

Suggestions:
Teach users how to configure Outlook/Exchange themselves – REJECTED. Users cannot be expected to read instructions that is what IT is for.
Accepted solution: Use Office Customization Wizard to create an Outlook Profile. Check at each logon if Outlook is configure, if it is not load the corresponding Outlook/Exchange profile.

Future Versions:
Future versions will use PowerShell as I am migrating to PowerShell. Using PowerShell’s native syntax you can enumerate Outlook.exe’s location and call that versus static entries in the file or using reg.exe

rem #***********************************************************************
rem # "Configure-Outlook.bat"
rem #
rem # Written by Aaron Wurthmann (aaron <AT> wurthmann <DOT> com)
rem # If you edit please keep my name as an original author and
rem # keep me apprised of the changes, see email address above.
rem # This code may not be used for commercial purposes.
rem # You the executor,runner,user accept all liability.
rem # This code comes with ABSOLUTELY NO WARRANTY.
rem # You may redistribute copies of the code under the terms of the GPL v2.
rem # -----------------------------------------------------------------------
rem # 2010.03.01 ver FINAL
rem #
rem # Summary:
rem # Configures Outlook using referenced Outlook Profile, created by Office
rem # Custom Install Wizard.
rem # Future Versions:
rem # Future versions will use PowerShell as I am migrating to PowerShell. 
rem # Using PowerShell’s native syntax you can enumerate Outlook.exe’s
rem # location and call that versus static entries in the file or using reg.exe
rem #************************************************************************

@echo off rem title Configure Outlook Module set errorlevel= set strProfileDir= set strOutlookDir= set ExchServer=EXCHANGE.DOMAIN.EXT set OWAServer=OWA.DOMAIN.EXT set MailProfile=Outlook set ExchProfile=exch_cach_ssl.PRF rem Check for Server OS, if server OS exit %logonserver%netlogontoolsREG.EXE query "HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionProductName" | findstr Server>nul && goto :EoF rem Determine Outlook version, 2003 or 2007 if exist "%ProgramFiles(x86)%Microsoft OfficeOFFICE11OUTLOOK.EXE" set strOutlookDir=%ProgramFiles(x86)%Microsoft OfficeOFFICE11 if exist "%ProgramFiles(x86)%Microsoft OfficeOFFICE12OUTLOOK.EXE" set strOutlookDir=%ProgramFiles(x86)%Microsoft OfficeOFFICE12 if exist "%ProgramFiles%Microsoft OfficeOFFICE11OUTLOOK.EXE" set strOutlookDir=%ProgramFiles%Microsoft OfficeOFFICE11 if exist "%ProgramFiles%Microsoft OfficeOFFICE12OUTLOOK.EXE" set strOutlookDir=%ProgramFiles%Microsoft OfficeOFFICE12 if not exist "%strOutlookDir%" goto :EoF rem Determine XP, Vista or Later ver | findstr /c:"Version 6.">nul && set strProfileDir=%USERPROFILE%AppDataRoamingMicrosoftOutlook ver | findstr /c:"Version 5.">nul && set strProfileDir=%USERPROFILE%Local SettingsApplication DataMicrosoftOutlook rem If Profile Exist Exit if exist "%strProfileDir%*.*" goto :EoF rem Check for Account Exclusions, If Excluded Exit FOR /F "usebackq delims== " %%a IN (%logonserver%netlogonmodulesexclusionsexchange.log) DO if /i '%%a'=='%username%' goto :EoF :import rem Import Profle start "" "%strOutlookDir%OUTLOOK.EXE" /importprf %logonserver%netlogonmodulesexchange-profiles%ExchProfile%

Example Outlook Profile – exch_cach_ssl.PRF


; **************************************************************
; Section 1 - Profile Defaults
; **************************************************************

[General]
Custom=1
ProfileName=Exchange with SSL Profile
DefaultProfile=Yes
OverwriteProfile=Yes
ModifyDefaultProfileIfPresent=TRUE
; **************************************************************
; Section 2 - Services in Profile
; **************************************************************

[Service List]
ServiceX=Microsoft Outlook Client
ServiceEGS=Exchange Global Section
Service1=Microsoft Exchange Server
ServiceEGS=Exchange Global Section

;***************************************************************
; Section 3 - List of internet accounts
;***************************************************************

[Internet Account List]

;***************************************************************
; Section 4 - Default values for each service.
;***************************************************************

[ServiceX]
CachedExchangeMode=0x00000002
CachedExchangeSlowDetect=TRUE

[ServiceEGS]
CachedExchangeConfigFlags=0x00000100
MailboxName=%UserName%
HomeServer=%ExchServer%
RPCoverHTTPflags=0x002b
RPCProxyServer=%OWAServer%
RPCProxyPrincipalName=
RPCProxyAuthScheme=0x0001

[Service1]
OverwriteExistingService=Yes
UniqueService=Yes
MailboxName=%UserName%
HomeServer=%ExchServer%
OfflineAddressBookPath=%USERPROFILE%local settingsapplication datamicrosoftoutlook
OfflineFolderPath=%USERPROFILE%local settingsapplication datamicrosoftoutlookoutlook.ost
AccountName=Microsoft Exchange Server

;***************************************************************
; Section 5 - Values for each internet account.
;***************************************************************

;***************************************************************
; Section 6 - Mapping for profile properties
;***************************************************************

[Microsoft Exchange Server]
ServiceName=MSEMS
MDBGUID=5494A1C0297F101BA58708002B2A2517
MailboxName=PT_STRING8,0x6607
HomeServer=PT_STRING8,0x6608
OfflineAddressBookPath=PT_STRING8,0x660E
OfflineFolderPath=PT_STRING8,0x6610

[Exchange Global Section]
SectionGUID=13dbb0c8aa05101a9bb000aa002fc45a
MailboxName=PT_STRING8,0x6607
HomeServer=PT_STRING8,0x6608
RPCoverHTTPflags=PT_LONG,0x6623
RPCProxyServer=PT_UNICODE,0x6622
RPCProxyPrincipalName=PT_UNICODE,0x6625
RPCProxyAuthScheme=PT_LONG,0x6627
CachedExchangeConfigFlags=PT_LONG,0x6629

[Microsoft Mail]
ServiceName=MSFS
ServerPath=PT_STRING8,0x6600
Mailbox=PT_STRING8,0x6601
Password=PT_STRING8,0x67f0
RememberPassword=PT_BOOLEAN,0x6606
ConnectionType=PT_LONG,0x6603
UseSessionLog=PT_BOOLEAN,0x6604
SessionLogPath=PT_STRING8,0x6605
EnableUpload=PT_BOOLEAN,0x6620
EnableDownload=PT_BOOLEAN,0x6621
UploadMask=PT_LONG,0x6622
NetBiosNotification=PT_BOOLEAN,0x6623
NewMailPollInterval=PT_STRING8,0x6624
DisplayGalOnly=PT_BOOLEAN,0x6625
UseHeadersOnLAN=PT_BOOLEAN,0x6630
UseLocalAdressBookOnLAN=PT_BOOLEAN,0x6631
UseExternalToHelpDeliverOnLAN=PT_BOOLEAN,0x6632
UseHeadersOnRAS=PT_BOOLEAN,0x6640
UseLocalAdressBookOnRAS=PT_BOOLEAN,0x6641
UseExternalToHelpDeliverOnRAS=PT_BOOLEAN,0x6639
ConnectOnStartup=PT_BOOLEAN,0x6642
DisconnectAfterRetrieveHeaders=PT_BOOLEAN,0x6643
DisconnectAfterRetrieveMail=PT_BOOLEAN,0x6644
DisconnectOnExit=PT_BOOLEAN,0x6645
DefaultDialupConnectionName=PT_STRING8,0x6646
DialupRetryCount=PT_STRING8,0x6648
DialupRetryDelay=PT_STRING8,0x6649

[Personal Folders]
ServiceName=MSPST MS
Name=PT_STRING8,0x3001
PathToPersonalFolders=PT_STRING8,0x6700 
RememberPassword=PT_BOOLEAN,0x6701
EncryptionType=PT_LONG,0x6702
Password=PT_STRING8,0x6703

[Unicode Personal Folders]
ServiceName=MSUPST MS
Name=PT_UNICODE,0x3001
PathToPersonalFolders=PT_STRING8,0x6700 
RememberPassword=PT_BOOLEAN,0x6701
EncryptionType=PT_LONG,0x6702
Password=PT_STRING8,0x6703

[Outlook Address Book]
ServiceName=CONTAB

[LDAP Directory]
ServiceName=EMABLT
ServerName=PT_STRING8,0x6600
UserName=PT_STRING8,0x6602
UseSSL=PT_BOOLEAN,0x6613
UseSPA=PT_BOOLEAN,0x6615
DisableVLV=PT_LONG,0x6616
DisplayName=PT_STRING8,0x3001
ConnectionPort=PT_STRING8,0x6601
SearchTimeout=PT_STRING8,0x6607
MaxEntriesReturned=PT_STRING8,0x6608
SearchBase=PT_STRING8,0x6603

[Microsoft Outlook Client]
SectionGUID=0a0d020000000000c000000000000046
FormDirectoryPage=PT_STRING8,0x0270
WebServicesLocation=PT_STRING8,0x0271
ComposeWithWebServices=PT_BOOLEAN,0x0272
PromptWhenUsingWebServices=PT_BOOLEAN,0x0273
OpenWithWebServices=PT_BOOLEAN,0x0274
CachedExchangeMode=PT_LONG,0x041f
CachedExchangeSlowDetect=PT_BOOLEAN,0x0420

[Personal Address Book]
ServiceName=MSPST AB
NameOfPAB=PT_STRING8,0x001e3001
Path=PT_STRING8,0x001e6600
ShowNamesBy=PT_LONG,0x00036601

; ************************************************************************
; Section 7 - Mapping for internet account properties.  DO NOT MODIFY.
; ************************************************************************

[I_Mail]
AccountType=POP3
;--- POP3 Account Settings ---
AccountName=PT_UNICODE,0x0002
DisplayName=PT_UNICODE,0x000B
EmailAddress=PT_UNICODE,0x000C
;--- POP3 Account Settings ---
POP3Server=PT_UNICODE,0x0100
POP3UserName=PT_UNICODE,0x0101
POP3UseSPA=PT_LONG,0x0108
Organization=PT_UNICODE,0x0107
ReplyEmailAddress=PT_UNICODE,0x0103
POP3Port=PT_LONG,0x0104
POP3UseSSL=PT_LONG,0x0105
; --- SMTP Account Settings ---
SMTPServer=PT_UNICODE,0x0200
SMTPUseAuth=PT_LONG,0x0203
SMTPAuthMethod=PT_LONG,0x0208
SMTPUserName=PT_UNICODE,0x0204
SMTPUseSPA=PT_LONG,0x0207
ConnectionType=PT_LONG,0x000F
ConnectionOID=PT_UNICODE,0x0010
SMTPPort=PT_LONG,0x0201
SMTPUseSSL=PT_LONG,0x0202
ServerTimeOut=PT_LONG,0x0209
LeaveOnServer=PT_LONG,0x1000

[IMAP_I_Mail]
AccountType=IMAP
;--- IMAP Account Settings ---
AccountName=PT_UNICODE,0x0002
DisplayName=PT_UNICODE,0x000B
EmailAddress=PT_UNICODE,0x000C
;--- IMAP Account Settings ---
IMAPServer=PT_UNICODE,0x0100
IMAPUserName=PT_UNICODE,0x0101
IMAPUseSPA=PT_LONG,0x0108
Organization=PT_UNICODE,0x0107
ReplyEmailAddress=PT_UNICODE,0x0103
IMAPPort=PT_LONG,0x0104
IMAPUseSSL=PT_LONG,0x0105
; --- SMTP Account Settings ---
SMTPServer=PT_UNICODE,0x0200
SMTPUseAuth=PT_LONG,0x0203
SMTPAuthMethod=PT_LONG,0x0208
SMTPUserName=PT_UNICODE,0x0204
SMTPUseSPA=PT_LONG,0x0207
ConnectionType=PT_LONG,0x000F
ConnectionOID=PT_UNICODE,0x0010
SMTPPort=PT_LONG,0x0201
SMTPUseSSL=PT_LONG,0x0202
ServerTimeOut=PT_LONG,0x0209
CheckNewImap=PT_LONG,0x1100
RootFolder=PT_UNICODE,0x1101

[INET_HTTP]
AccountType=HOTMAIL
Account=PT_UNICODE,0x0002
HttpServer=PT_UNICODE,0x0100
UserName=PT_UNICODE,0x0101
Organization=PT_UNICODE,0x0107
UseSPA=PT_LONG,0x0108
TimeOut=PT_LONG,0x0209
Reply=PT_UNICODE,0x0103
EmailAddress=PT_UNICODE,0x000C
FullName=PT_UNICODE,0x000B
Connection Type=PT_LONG,0x000F
ConnectOID=PT_UNICODE,0x0010

PowerShell Script Export-ADGroupToHTML.ps1

Project Objective:
Make one place and one place only a repository for employee contact information.

Problem to be solved:
Curently there are two places people retrieve contact information. Static web page made from an Excel spreadsheet everyone has Full access to and of course the second Outlook (Exchange/Active Directory).

Suggestions:
Sync the web page with the information in Active Directory – REJECTED (Security risk: tamper accidental or otherwise could occur with other people’s information.
Accepted Solution – Allow users to change their own information in Active Directory with GALMod32, export contact information to a formated html file that uses the site’s CSS and Sortable Table to allow viewers to sort the contact information anyway they see fit.

Future Versions:
This code needs to be rewritten with proper procedures instead of a single massive pipe. I would also like to be able to add a Manager collum however in its current form (one large pipe) that isn’t easy as the Manager field resolves to a DN and resolving that DN inline while preservig the object being piped isn’t trivial. That’s what happens when you write a massive pipe. LOL

# Export-ADgroupToHTML.ps1
#
# Written by Aaron Wurthmann (aaron <AT> wurthmann <DOT> com)
#    co-written by Tobias Speckbacher
#
# If you edit please keep my name as an original author and
# keep me apprised of the changes, see email address above.
# This code may not be used for commercial purposes.
# You the executor,runner,user accept all liability.
# This code comes with ABSOLUTELY NO WARRANTY.
# You may redistribute copies of the code under the terms of the GPL v2.
# -----------------------------------------------------------------------
# Prerequisite:
# Written for PowerShell v2
# Quest ActiveRoles Management Shell for Active Directory Plugin Required
#     http://www.quest.com/powershell/activeroles-server.aspx
# -----------------------------------------------------------------------
# 2010.02.01 ver 2.1
#
# Summary:
# Enumerates an Active Directory Group then Exports group members'
# contact information into a formatted HTML file. Checks to see if there
# will be more than a 10% change to the file. If there will be, abort.
# I built this feature in mostly as a proof of concept for another script
# but to basically insure that for some freakish reason the file doesn't
# get blanked out or all the records removed.
#
# Notes:
# This was/is my first PowerShell script and what won me over
# to using PowerShell. The script does need a re-write with everything
# I have learned and some functions I plan on returning to this script and
# re-writting it someday. For the most part PowerShell is new to me so as
# such the "main" function is a series of pipes. One thing you will need
# to watch out for, since the main is a series of pipes, is memory usage.
# After running this script a few times in a single shell I noticed
# powershell.exe was using more and more memory. While testing and
# tweaking you may need to exit your shell and restart a new one.
# I dont "think" this is a problem if the script is running as a
# Scheduled Task, just when its run over and over in your shell.
#************************************************************************

#Edit Varibles Here, File Paths and Names, DN for All users group, CSS Style
$temphtml="C:inetpubwwwrootwssVirtualDirectories80contacttemp.htm"
$finalhtm="C:inetpubwwwrootwssVirtualDirectories80contactdata.htm"

$allGroup="CN=Domain Users,OU=Users,DC=company,DC=ext"
$properties='Name', 'Title', 'telephoneNumber', 'mobile', 'HomePhone', 'facsimileTelephoneNumber','Notes'

$head='
    <meta name="GENERATOR" content="Microsoft SharePoint" />
    <meta name="progid" content="SharePoint.WebPartPage.Document" />
    <meta HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
    <meta HTTP-EQUIV="Expires" content="0" /><META NAME="ROBOTS" CONTENT="NOHTMLINDEX"/>
    <script type="text/javascript" src="sortable.js"></script>
    <title>Company Contact List</title>
    <link rel="stylesheet" type="text/css" href="_layouts/1033/styles/core.css?rev=5msmprmeONfN6lJ3wtbAlA%3D%3D"/>
    <link rel="stylesheet" type="text/css" id="onetidThemeCSS" href="_themes/Cardinal/Card1011-65001.css?rev=12%2E0%2E0%2E6421"/>
    <script type="text/javascript" language="javascript" src="_layouts/1033/init.js?rev=qX%2BG3yl4pldKy9KbPLXf9w%3D%3D"></script>
    <script type="text/javascript" language="javascript" src="_layouts/1033/core.js?rev=CNBZRdV1h3pKuA7LsMXf3w%3D%3D" defer></script>
    <script type="text/javascript" language="javascript" src="_layouts/1033/ie55up.js?rev=Ni7%2Fj2ZV%2FzCvd09XYSSWvA%3D%3D"></script>
    <link type="text/xml" rel="alternate" href="_vti_bin/spdisco.aspx" />
    <META Name="CollaborationServer" Content="SharePoint Team Web Site">
    <style type="text/css">
        a img {border: 0;}
        table.sortable {border-width:4px; border-style:hidden; border-color:none; border-collapse:collapse; width:150%;}
        table.sortable th, table.sortable td {font-size:1em; text-align: left; padding: 4px; border-style: solid; border-color:none;}
        table.sortable th {border-width: 0px 0px 3px 0px;background-color: #ccc;}
        table.sortable td {font-size:0.9em; border-width:0px 0px 0px 0px; border-color:#444}
        table.sortable tr.odd td {background-color: #ddd;}
        table.sortable tr.even td {background-color: #fff;}
        table.sortable tr.sortbottom td {border-top: 1px solid #444;background-color: #ccc;font-weight: bold;}
    </style>'
#End Editable Area

#region Main: If not present add PSSnapin Quest.ActiveRoles.ADManagement, Enumerate Users in All group, Select Desired Properties,...
# ...Sort by Name, Output as temporary HTML file with above header, Replace Table Header with formated one
# The line below is expected to error then recover, I dont know how to properly check then add Snapins yet
if (Get-PSSnapin -name Quest.ActiveRoles.ADManagement) {} else {Add-PSSnapin Quest.ActiveRoles.ADManagement}

Get-QADGroupMember $allGroup -Indirect |
where {$_.Type -eq ("User")} |
Get-QADUser |
Select-Object -property $properties |
Sort-Object -Property 'Name' |
ConvertTo-Html -head $head |
Foreach-Object {$_ -creplace '<table>','<table class="sortable" id="employees">'} |
Foreach-Object {$_ -creplace '<tr><th>Name</th><th>Title</th><th>telephoneNumber</th><th>mobile</th><th>HomePhone</th><th>facsimileTelephoneNumber</th><th>Notes</th></tr>','<tr><th>Name</th><th>Title</th><th>Office              </th><th>Mobile              </th><th>Home               </th><th>Fax                </th><th>Notes</th></tr>'} |
Out-File $temphtml
#endregion

# Create New Data.htm IF Data.htm already exists and If temporary HTML file is between 10% smaller or 10% larger
if (test-path $finalhtm) {
    $tempfileSize=Get-ChildItem $temphtml | ForEach-Object {($_.Length)}
    $finalhtmSize=Get-ChildItem $finalhtm | ForEach-Object {($_.Length)}
    $fileDiff=($finalhtmSize/$tempfileSize)
    if ($fileDiff -gt 0.9) {
        if ($fileDiff -lt 1.1) {
            Remove-Item $finalhtm
            Rename-Item $temphtml -NewName $finalhtm
            }
        }
    }
#endregion

VisualBasic Script check_eventlogs.wsf

Project Objective:
Create a Nagios addon to be run with NRPE/NSClient++ that checks the Windows event logs for errors.

Problem to be solved:
Increased monitoring of Windows systems. Get notified of any and all errors as they happen opposed to after something worse happens be it hard drive failure, service offline, etc.

Suggestions:
Use existing native Nagios module – REJECED Existing module doesn’t have enough filter capability to prevent IT from being spammed with EVERY single request AND doesnt provide verbose output/what the error even is, just that there was an error.
Accepted Solution: Write our own module to use with a WSF wrapper (as was the norm on NagiosExchange) at the time.

Future Versions:
The original version of this script and another were posted on Nagios Exchange. For whatever reason they are missing now, even though they were quite popular for some time. Future versions will utilize PowerShell over VBS as many of the commands used here are native and faster in PowerShell.

'#***********************************************************************
'# "Check_EventLogs.wsf""
'#
'# "Insipred" by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'#
'#
'# If you edit please keep my name as an original author and
'# keep me apprised of the changes, see email address above.
'# This code may not be used for commercial purposes.
'# You the executor,runner,user accept all liability.
'# This code comes with ABSOLUTELY NO WARRANTY.
'# You may redistribute copies of the code under the terms of the GPL v2.
'# -----------------------------------------------------------------------
'# Notes:
'# The core of this script was re-written by two collegues of mine.
'# I was having problems with my previous attempts at solving this problem
'# So I mailed what I had off to a friend, when it came back it was re-written.
'# Thank you dstenseth and acakir, may the foos gods smile upon thee.
'# For debugging I recomend testing your queries out with wbemtest.
'# I adapted this script from ronald van vugt's Check_Services.wsf
'# -----------------------------------------------------------------------
'# 2007.07.31 ver FINAL
'#
'# Summary:
'# Checks System and Application event logs for Warnings and Errors;
'# If an error(s) are found, send verbose information including error message.
'#************************************************************************

<job>
<runtime>
  <description>

Check_EventLogs (nrpe_nt-plugin) 1.0
This nrpe_nt plugin come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License v2.

  </description>
    <named
      name="h"
      helpstring="Help"
      type="simple"
      required="false"
    />
  />

  <example>

  You do not need a string for this plugin.

  This script checks the event logs for Warnings and Errors;
  If an error is found, verbose information is sent back. A
  registry key is written in order to track when the last time
  checked was.

  Usage:
  command [check_eventlogs]=c:Windowssystem32cscript.exe //NoLogo //T:10 check_eventlogs.wsf

  </example>

</runtime>

<script language="VBScript">

'*******************************************************************
' Help
'*******************************************************************
If Wscript.Arguments.Named.Exists("h") Then
      Wscript.Echo "Plugin help screen:"
      Wscript.Arguments.ShowUsage()
      Wscript.Quit(0)
End If

'*******************************************************************
' Main
'*******************************************************************
Dim dtmFrom
Dim errCount
Dim intResultWarning
Dim intResultError
Dim strResultWarning
Dim strResultError
Dim strComputer
Dim oReg

Const AppKey = "SYSTEMCurrentControlSetServicesNRPE_NT"
Const AppVal = "LastExec"
Const CONVERT_TO_LOCAL_TIME = True
Const ForReading = 1
Const ForWriting = 2
Const HKLM = &H80000002

intResultWarning = 0
intResultError = 0
ExecDate_Current = CDate(Now)
strComputer = "."

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\" & strComputer & "rootdefault:StdRegProv")
oReg.GetStringValue HKLM,AppKey,AppVal,ExecDate_Last 

if IsNull ( ExecDate_Last ) then
        oReg.CreateKey HKLM, AppKey
        ExecDate_Last = CDate(Now)
else
        ExecDate_Last = CDate(ExecDate_Last)
end If

Set dtmFrom = CreateObject("WbemScripting.SWbemDateTime")
dtmFrom.SetVarDate ExecDate_Last, CONVERT_TO_LOCAL_TIME
Set dtmTo = CreateObject("WbemScripting.SWbemDateTime")
dtmTo.SetVarDate ExecDate_Current, CONVERT_TO_LOCAL_TIME

Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")
query = "SELECT * FROM Win32_NTLogEvent WHERE (Logfile='Application' AND Type<>'Information' AND TimeWritten >='" & dtmFrom & "')_
         or (Logfile='System' AND Type<>'Information' AND TimeWritten >='" & dtmFrom & "') "

Set colEvents = objWMI.ExecQuery(query)
oReg.SetStringValue HKLM,AppKey,AppVal,CStr(Now)
errCount = colEvents.Count

if ( errCount > 0 ) then

        For Each objEvent in colEvents
                if objEvent.Type = "Error" then
                        intResultError = 2
                        if strResultError <> "" then
                                strResultError = _
                                objEvent.Logfile & " Log - Error!! " & vbCRLF &_
                                "Source: " & objEvent.SourceName & vbCRLF &_
                                "Event Code: " & objEvent.EventCode & vbCRLF &_
                                "Message: " & objEvent.Message & " " & vbCRLF &_
                                vbCRLF & strResultError
                        else
                                strResultError = _
                                objEvent.Logfile & " Log - Error!! " & vbCRLF &_
                                "Source: " & objEvent.SourceName & vbCRLF &_
                                "Event Code: " & objEvent.EventCode & vbCRLF &_
                                "Message: " & objEvent.Message & " " & vbCRLF
                        end if
                else
                        if objEvent.Type = "Warning" then
                                intResultWarning = 1
                                if strResultWarning <> "" then
                                        strResultWarning = _
                                        objEvent.Logfile & " Log - Warning! " & vbCRLF &_
                                        "Source: " & objEvent.SourceName & vbCRLF &_
                                        "Event Code: " & objEvent.EventCode & vbCRLF &_
                                        "Message: " & objEvent.Message & " " & vbCRLF &_
                                        vbCRLF & strResultWarning
                                else
                                        strResultWarning = _
                                        objEvent.Logfile & " Log - Warning! " & vbCRLF &_
                                        "Source: " & objEvent.SourceName & vbCRLF &_
                                        "Event Code: " & objEvent.EventCode & vbCRLF &_
                                        "Message: " & objEvent.Message & " " & vbCRLF
                                end if
                        end if
                end if
        next
end if

Select case intResultWarning + intResultError
  Case 0 wscript.echo "No Errors or Warnings found in System or Application Event Logs"
         wscript.quit(0)
  Case 1 wscript.echo strResultWarning
         wscript.quit(1)
  Case 2 wscript.echo strResultError
         wscript.quit(2)
  Case 3 wscript.echo strResultWarning & vbCRLF & strResultError
         wscript.quit(2)
end select

' ----- End of Script -----------------------------------------------------------------

Function WMIDateStringToDate(dtmEventDate)
    WMIDateStringToDate = CDate(Mid(dtmEventDate, 5, 2) & "/" & _
        Mid(dtmEventDate, 7, 2) & "/" & Left(dtmEventDate, 4) _
            & " " & Mid (dtmEventDate, 9, 2) & ":" & _
                Mid(dtmEventDate, 11, 2) & ":" & Mid(dtmEventDate, _
                    13, 2))
End Function
</script>
</job>

VisualBasic Script Printers-Site-Install.vbs

Project Objective:
Reduce total cost of ownership/administration time on adding/replacing printers by automatically adding them at logon.

Problem to be solved:
This script replaces my existing batch script that uses con2prt.exe. The problem with con2prt.exe is that it isn’t great at removing network printers without removing PDF writers and or local attached printers.

Future Versions:
At some point I’d like to revisit this script and build some more intelligence into site and printer selection. I’d like for it to leverage AD to determine a system’s or user’s site then install printers accordingly.

'
' Printers-Site-Install.vbs
'
' Written by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'
' If you edit please keep my name as an original author and
' keep me apprised of the changes, see email address above.
' This code may not be used for commercial purposes.
' You the executor, runner, user accept all liability.
' This code comes with ABSOLUTELY NO WARRANTY.
' You may redistribute copies of the code under the terms of the GPL v2.
' -----------------------------------------------------------------------
' 2007-05-02 version 2
'
' Summary:
' Reduce total cost of ownership/administration time on adding/replacing 
' printers by automatically adding them at logon.
'
' -----------------------------------------------------------------------


Dim WshShell, oExec, output
Dim fso, tmpFile
Dim strComputerName
Dim strBuff
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
Set objADSysInfo = CreateObject("ADSystemInfo")

' EDIT THIS SECTION WITH YOUR INFO
' If Site X then Printer X, if Site Y then Printer Y
if objADSysInfo.SiteName="San-Jose-Site" then
 strSiteServer="MyPrintServer"
end if

' END EDIT SECTION
 
' Remove Any Other (other than Site Print Server) Network Printers
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery ("Select * from Win32_Printer WHERE Name LIKE '%\\\\%'")
For Each objPrinter in colInstalledPrinters
 ' WScript.Echo objPrinter.Name
 tmp = InStr(1, objPrinter.Name, strSiteServer, 1)
 if tmp = 0 Then
  WshNetwork.removePrinterConnection objPrinter.Name, true, true
 end if
Next
' Enumerate Site Printer Server and Add Connections if Needed
Set oExec = WshShell.Exec("net view \\" & strSiteServer)
strBuff = oExec.StdOut.ReadAll
arrayBuff = split(strBuff, vbCrLf, -1, 1)
for each buff in arrayBuff
        result = InStr(1, buff, "Print ", 1)
        if result > 0 Then
         printerName = split(buff, " ", -1, 1)(0)
          connName = "\\" & strSiteServer & "\" & printerName
                 WshNetwork.AddWindowsPrinterConnection connName
        end if
next