29 December 2015

Microsoft Office Updater

One of the things that has annoyed me in the past is having to keep the Microsoft Office Updates folder up-to-date with the latest .MSP files. The reason I bother with keeping the Updates folder up-to-date is because it speeds up the process of building a golden image, which in my environment, Office is installed during that phase. To automate this process, I created an automatic deployment rule in SCCM that keeps the Microsoft Office software update group up-to-date with the latest Office updates. To bridge those updates with the Updates folder under the Office installation directory, I wrote the script below.

The script is setup to run as a scheduled task on the SCCM server once a week. It does not have to be setup to execute on a schedule, but it does make for one less thing to keep up with. The variables you will have to modify are $Country, $Source, and $Destination. You specify which country you need to include in the $Country variable on line 29. If you need multiple countries, you will have to modify this script. $Source will be the directory where the Deployment Package is written to on line 30. $Destination is the location of the Microsoft Office Updates folder on line 31. The files located on the SCCM server are all .CAB files, so this script automatically extracts the .MSP files from the .CAB files and places them in the Updates directory.


There is a newer version of this script located here.


1:  <#       
2:       .NOTES  
3:       ===========================================================================  
4:        Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.99  
5:        Created on:       12/29/2015 9:50 AM  
6:        Created by:       Mick Pletcher  
7:        Organization:         
8:        Filename:        OfficeUpdater.ps1  
9:       ===========================================================================  
10:       .DESCRIPTION  
11:            This script will keep the Updates folder populated with the latest Office  
12:            updates that SCCM has downloaded. It should be setup to execute as a   
13:            scheduled task on the SCCM server. I suggest executing it once a week.   
14:  #>  
15:    
16:  #Declare Variables  
17:  Set-Variable -Name Counter -Value 0 -Scope Local -Force  
18:  Set-Variable -Name Country -Scope Local -Force  
19:  Set-Variable -Name Destination -Scope Local -Force  
20:  Set-Variable -Name Executable -Scope Local -Force  
21:  Set-Variable -Name File -Scope Local -Force  
22:  Set-Variable -Name Files -Scope Local -Force  
23:  Set-Variable -Name Folder -Scope Local -Force  
24:  Set-Variable -Name Folders -Scope Local -Force  
25:  Set-Variable -Name Output -Scope Local -Force  
26:  Set-Variable -Name Parameters -Scope Local -Force  
27:  Set-Variable -Name Source -Scope Local -Force  
28:    
29:  $Country = "en-us"  
30:  $Source = "<SCCM Updates Source Directory>"  
31:  $Destination = "<Microsoft Office Updates folder>"  
32:  $Executable = $env:windir + "\System32\expand.exe"  
33:  If ($Country -notcontains "`*") {  
34:       $Country = "*" + $Country + "*"  
35:  }  
36:  $Folders = Get-ChildItem -Path $Source -Recurse | ?{ $_.PSIsContainer }  
37:  foreach ($Folder in $Folders) {  
38:       cls  
39:       $Counter++  
40:       $Output = "Processing " + $Counter + " of " + $Folders.Count  
41:       Write-Host $Output  
42:       $Files = Get-ChildItem -Path $Folder.Fullname -Recurse  
43:       foreach ($File in $Files) {  
44:            If (($File.Name -like $Country) -or ($File.Name -like "*none*")) {  
45:                 $Parameters = [char]34 + $File.FullName + [char]34 + [char]32 + [char]34 + $Destination + [char]34 + [char]32 + "-f:*"  
46:                 $ErrCode = (Start-Process -FilePath $Executable -ArgumentList $Parameters -Wait -Passthru).ExitCode  
47:                 #Copy-Item -Path $File.FullName -Destination $Destination -Force  
48:            }  
49:       }  
50:  }  
51:    
52:  #Cleanup Variables  
53:  Remove-Variable -Name Counter -Scope Local -Force  
54:  Remove-Variable -Name Country -Scope Local -Force  
55:  Remove-Variable -Name Destination -Scope Local -Force  
56:  Remove-Variable -Name Executable -Scope Local -Force  
57:  Remove-Variable -Name File -Scope Local -Force  
58:  Remove-Variable -Name Files -Scope Local -Force  
59:  Remove-Variable -Name Folder -Scope Local -Force  
60:  Remove-Variable -Name Folders -Scope Local -Force  
61:  Remove-Variable -Name Output -Scope Local -Force  
62:  Remove-Variable -Name Parameters -Scope Local -Force  
63:  Remove-Variable -Name Source -Scope Local -Force  
64:    

28 December 2015

Automating the Creation of Software Update Groups in SCCM

I have been working on automating the tasks of deploying Windows updates each month. You may think why is there a need for this when SCCM has the Automatic Deployment Rules. Some companies have to review the updates before hand if they have applications that are vulnerable to breaking from windows updates.

This script is the first of a series of steps to achieve this task. This script will automatically create a Software Update Group in SCCM. To further assist the admins, I have also included the ability for the script to generate an excel spreadsheet with a list of the updates that were added to the newly created Update Group. The script then emails the spreadsheet to the designated admin(s). This allows for two things: 1) It reminds the admin that it's that time of the month again, and 2) It allows the admin to review the updates before downloading them, if there are any that need to be removed. That is why I am not automating the package creation portion.

There are three variables that need to be populated: $EmailAddresses, $OperatingSystem, and $Architecture. You can enter multiple email addresses in the $EmailAddresses array. The two optional variables are $UpdateTypes and $Filters. Do not change $Updates.

The script has the ability to specify updates using three different criteria. Set-TimeSpanByMonthsOld lets you specify to include all updates say one month old. My firm deploys updates one month old so that if there are issues in newly released ones, they will typically have been resolved after a month. Say it is currently December, this function will specify all updates from 11/1 to 11/30.

The second criteria is Set-TimeSpanByDatePeriod. This allows for you to specify a specific date range if you are doing a one-off deployment.

The third is Set-TimeSpanAllUpdatesBeforeDate. This allows for you to specify all updates before a specific date to be included.

This script has to be executed on the SCCM server. I have set the script up as a scheduled task that is executed the second Wednesday of every month. You will need to change line 19 to the location of the SCCM module on your server.

I have commented out a few examples within the script.

You can download the script from here.




1:  <#       
2:       .NOTES  
3:       ===========================================================================  
4:        Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.98  
5:        Created on:       12/28/2015 9:08 AM  
6:        Created by:       Mick Pletcher  
7:        Organization:         
8:        Filename:        SoftwareUpdateGroupCreator.ps1  
9:       ===========================================================================  
10:       .DESCRIPTION  
11:            This script will create a new software update group each month. It then  
12:            generates an email to send to the admin(s) to review what updates  
13:            were put into the new update group. It does not download the updates so  
14:            that if an update needs to be removed, it can be done before it is   
15:            downloaded.   
16:              
17:  #>  
18:    
19:  Import-Module "D:\Program Files\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"  
20:    
21:  function Get-Updates {  
22:       param ([String]$Architecture, [String]$OperatingSystem, [String]$Namespace, $Updates )  
23:         
24:       $Updates = @()  
25:       $Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace  
26:       $Updates = $Updates | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) }  
27:       If ($Architecture -eq "x86") {  
28:            $Updates = $Updates | where-object { ($_.LocalizedDisplayName -notmatch "x64") }  
29:       } elseif ($Architecture -eq "x64") {  
30:            #$Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) -and ($_.LocalizedDisplayName -match "x64-based Systems") }  
31:            $Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) -and ($_.LocalizedDisplayName -match "x64") }  
32:       }  
33:       Return $Updates  
34:  }  
35:    
36:  function Set-Filters {  
37:       param($Filters, $Updates, $UpdateTypes)  
38:         
39:       #Declare Variables  
40:       Set-Variable -Name Filter -Scope Local -Force  
41:       Set-Variable -Name UpdateType -Scope Local -Force  
42:         
43:       foreach ($Filter in $Filters) {  
44:            $Updates = $Updates | Where-Object { $_.LocalizedDisplayName -notmatch $Filter }  
45:       }  
46:       If ($UpdateTypes.Count -ge 1) {  
47:            foreach ($UpdateType in $UpdateTypes) {  
48:                 $Updates = $Updates | Where-Object { $_.LocalizedCategoryInstanceNames -match $UpdateType }  
49:            }  
50:            If ($UpdateTypes -eq "Update") {  
51:                 $Updates = $Updates | Where-Object { $_.LocalizedDisplayName -notmatch "Security Update" }  
52:            }  
53:       }  
54:       return $Updates  
55:         
56:       #Cleanup Variables  
57:       Remove-Variable -Name Filter -Scope Local -Force  
58:       Remove-Variable -Name UpdateType -Scope Local -Force  
59:  }  
60:    
61:  function Set-TimeSpanByMonthsOld {  
62:       param ($MonthsOld, $Updates)  
63:         
64:       #Declare Local Variables  
65:       Set-Variable -Name Day -Scope Local -Force  
66:       Set-Variable -Name Month -Scope Local -Force  
67:       Set-Variable -Name FirstDayOfMonth -Scope Local -Force  
68:       Set-Variable -Name LastDayOfMonth -Scope Local -Force  
69:       Set-Variable -Name Today -Scope Local -Force  
70:         
71:       If ($MonthsOld -ge 1) {  
72:            $MonthsOld = $MonthsOld * -1  
73:       }  
74:       $Today = Get-Date  
75:       $Month = $Today.AddMonths($MonthsOld)  
76:       $Day = $Month.Day  
77:       $FirstDayOfMonth = $Month.AddDays(($Day - 1) * -1)  
78:       $LastDayOfMonth = [System.DateTime]::DaysInMonth($Month.Year, $Month.Month)  
79:       $LastDayOfMonth = $LastDayOfMonth - 1  
80:       $LastDayOfMonth = $FirstDayOfMonth.AddDays($LastDayOfMonth)  
81:       $FirstDayOfMonth = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($FirstDayOfMonth)  
82:       $LastDayOfMonth = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($LastDayOfMonth)  
83:       $Updates = $Updates | Where { ($_.DateCreated -ge $FirstDayOfMonth) -and ($_.DateCreated -le $LastDayOfMonth) }  
84:       return $Updates  
85:         
86:       #Cleanup Local Variables  
87:       Remove-Variable -Name Day -Scope Local -Force  
88:       Remove-Variable -Name Month -Scope Local -Force  
89:       Remove-Variable -Name FirstDayOfMonth -Scope Local -Force  
90:       Remove-Variable -Name LastDayOfMonth -Scope Local -Force  
91:  }  
92:    
93:  function Set-TimeSpanByDatePeriod {  
94:       param ([String]$StartDate,  
95:            [String]$EndDate,  
96:            $Updates)  
97:         
98:       $StartDate = [DateTime]$StartDate  
99:       $StartDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($StartDate)  
100:       $EndDate = [DateTime]$EndDate  
101:       $EndDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($EndDate)  
102:       $Updates = $Updates | Where { ($_.DateCreated -ge $StartDate) -and ($_.DateCreated -le $EndDate) }  
103:       return $Updates  
104:  }  
105:    
106:  function Set-TimeSpanAllUpdatesBeforeDate {  
107:       param ([String]$StartDate, $Updates)  
108:         
109:       $StartDate = [DateTime]$StartDate  
110:       $StartDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($StartDate)  
111:       $Updates = $Updates | Where { $_.DateCreated -lt $StartDate }  
112:       return $Updates  
113:  }  
114:    
115:  function CreateSoftwareUpdateGroup {  
116:       param ($OperatingSystem, $Architecture, $Updates)  
117:         
118:       #Declare Variables  
119:       Set-Variable -Name Description -Scope Local -Force  
120:       Set-Variable -Name Month -Scope Local -Force  
121:       Set-Variable -Name SoftwareUpdateGroupName -Scope Local -Force  
122:       Set-Variable -Name SoftwareUpdates -Scope Local -Force  
123:       Set-Variable -Name Temp -Scope Local -Force  
124:       Set-Variable -Name Update -Scope Local -Force  
125:       Set-Variable -Name Year -Scope Local -Force  
126:         
127:       $SoftwareUpdates = @()  
128:       $Year = (Get-Date).Year  
129:       $Month = Get-Date -format "MMMM"  
130:       $SoftwareUpdateGroupName = $OperatingSystem + $Architecture + [char]32 + $Month + [char]45 + $Year  
131:       $Description = $SoftwareUpdateGroupName + [char]32 + "Updates"  
132:       foreach ($Update in $Updates) {  
133:            $SoftwareUpdates += ($Update.CI_ID)  
134:       }  
135:       cd BNA:  
136:       $TEMP = New-CMSoftwareUpdateGroup -Name $SoftwareUpdateGroupName -UpdateID $SoftwareUpdates -Description $Description  
137:       cd c:  
138:       $SoftwareUpdates = $null  
139:         
140:       #Cleanup Variables  
141:       Remove-Variable -Name Description -Scope Local -Force  
142:       Remove-Variable -Name Month -Scope Local -Force  
143:       Remove-Variable -Name SoftwareUpdateGroupName -Scope Local -Force  
144:       Remove-Variable -Name SoftwareUpdates -Scope Local -Force  
145:       Remove-Variable -Name Temp -Scope Local -Force  
146:       Remove-Variable -Name Update -Scope Local -Force  
147:       Remove-Variable -Name Year -Scope Local -Force  
148:  }  
149:    
150:  function ProcessLogFile {  
151:       param([String]$OperatingSystem, [String]$Architecture)  
152:         
153:       #Declare Local Variables  
154:       Set-Variable -Name LogFile -Scope Local -Force  
155:       Set-Variable -Name Month -Scope Local -Force  
156:       Set-Variable -Name Output -Scope Local -Force  
157:       Set-Variable -Name temp -Scope Local -Force  
158:         
159:       $Month = Get-Date -format "MMMM"  
160:       $OperatingSystem = $OperatingSystem -replace '\s',''  
161:       $LogFile = $env:TEMP + "\" + $OperatingSystem + $Architecture + $Month + "UpdatesReport.csv"  
162:       if ((Test-Path $LogFile) -eq $true) {  
163:            Remove-Item $LogFile -Force  
164:       }  
165:       if ((Test-Path $LogFile) -eq $false) {  
166:            $temp = New-Item $LogFile -ItemType file -Force  
167:            $Output = "Update Name, Article ID, Update Type, Release Date"  
168:            Out-File -FilePath $LogFile -InputObject $Output -Force -Encoding UTF8  
169:       }  
170:       Return $LogFile  
171:         
172:       #Cleanup Local Variables  
173:       Remove-Variable -Name LogFile -Scope Local -Force  
174:       Remove-Variable -Name Month -Scope Local -Force  
175:       Remove-Variable -Name Output -Scope Local -Force  
176:       Remove-Variable -Name temp -Scope Local -Force  
177:  }  
178:    
179:  function New-Report {  
180:       param($EmailAddressList, $Updates, $OperatingSystem, $Architecture)  
181:         
182:       #Declare Variables  
183:       Set-Variable -Name ArticleID -Scope Local -Force  
184:       Set-Variable -Name Body -Scope Local -Force  
185:       Set-Variable -Name DateCreated -Scope Local -Force  
186:       Set-Variable -Name EmailAddress -Scope Local -Force  
187:       Set-Variable -Name Month -Scope Local -Force  
188:       Set-Variable -Name Output -Scope Local -Force  
189:       Set-Variable -Name Subject -Scope Local -Force  
190:       Set-Variable -Name Update -Scope Local -Force  
191:         
192:       foreach ($Update in $Updates) {  
193:            $Update.LocalizedDisplayName = $Update.LocalizedDisplayName -replace ",", ""  
194:            $ArticleID = "KB" + $Update.ArticleID  
195:            [String]$DateCreated = [System.Management.ManagementDateTimeConverter]::ToDateTime($Update.DateCreated)  
196:            If ($Update.LocalizedCategoryInstanceNames -match "Security Updates") {  
197:                 $Output = $Update.LocalizedDisplayName + "," + $ArticleID + ",Security Update," + $DateCreated  
198:            } elseif (($Update.LocalizedCategoryInstanceNames -notmatch "Security Updates") -and ($Update.LocalizedCategoryInstanceNames -match "Update")) {  
199:                 $Output = $Update.LocalizedDisplayName + "," + $ArticleID + ",Update," + $DateCreated  
200:            } else {  
201:                 $Output = $Update.LocalizedDisplayName + "," + $ArticleID + ", ," + $DateCreated  
202:            }  
203:            Out-File -FilePath $LogFile -InputObject $Output -Append -Force -Encoding UTF8  
204:       }  
205:       $Month = Get-Date -format "MMMM"  
206:       $Subject = $OperatingSystem + $Architecture + [char]32 + $Month + [char]32 + "SCCM Windows Update List"  
207:       $Body = "List of Windows updates added to the" + $OperatingSystem + $Architecture + [char]32 + $Month + " software update group."  
208:       foreach ($EmailAddress in $EmailAddressList) {  
209:            Send-MailMessage -To $EmailAddress -From "engineers@wallerlaw.com" -Subject $Subject -Body $Body -Attachments $LogFile -SmtpServer "smtp.wallerlaw.com"  
210:       }  
211:       $EmailAddresses = $null  
212:         
213:       #Cleanup Variables  
214:       Remove-Variable -Name ArticleID -Scope Local -Force  
215:       Remove-Variable -Name Body -Scope Local -Force  
216:       Remove-Variable -Name DateCreated -Scope Local -Force  
217:       Remove-Variable -Name EmailAddress -Scope Local -Force  
218:       Remove-Variable -Name Month -Scope Local -Force  
219:       Remove-Variable -Name Output -Scope Local -Force  
220:       Remove-Variable -Name Subject -Scope Local -Force  
221:       Remove-Variable -Name Update -Scope Local -Force  
222:  }  
223:    
224:  #Declare Variables  
225:  Set-Variable -Name Architecture -Scope Local -Force  
226:  Set-Variable -Name EmailAddresses -Scope Local -Force  
227:  Set-Variable -Name Filters -Scope Local -Force  
228:  Set-Variable -Name LogFile -Scope Local -Force  
229:  Set-Variable -Name Namespace -Value root\sms\site_bna -Scope Local -Force  
230:  Set-Variable -Name OperatingSystem -Scope Local -Force  
231:  Set-Variable -Name Updates -Scope Local -Force  
232:  Set-Variable -Name UpdateTypes -Scope Local -Force  
233:    
234:  cls  
235:  $EmailAddresses = @("mick.pletcher@test.com")  
236:  $OperatingSystem = "Windows 7" #Windows 7, Windows 8.1, Windows Server 2012 R2  
237:  $Architecture = "x86" #x86, x64, or null  
238:  $UpdateTypes = @() #Security Update, Update, Service Pack  
239:  $Filters = @("Internet Explorer 8", "Internet Explorer 9", "Internet Explorer 10")  
240:  $Updates = @()  
241:    
242:  $LogFile = ProcessLogFile -OperatingSystem $OperatingSystem -Architecture $Architecture  
243:  $Updates = Get-Updates -Architecture $Architecture -Namespace $Namespace -OperatingSystem $OperatingSystem -Updates $Updates  
244:  $Updates = Set-Filters -Filters $Filters -Updates $Updates -UpdateTypes $UpdateTypes  
245:  $Updates = Set-TimeSpanByMonthsOld -MonthsOld 1 -Updates $Updates  
246:  #$Updates = Set-TimeSpanByDatePeriod -StartDate "1/1/2015" -EndDate "12/28/2015" -Updates $Updates  
247:  #$Updates = Set-TimeSpanAllUpdatesBeforeDate -StartDate "9/30/2015" -Updates $Updates  
248:  CreateSoftwareUpdateGroup -OperatingSystem $OperatingSystem -Updates $Updates -Architecture $Architecture  
249:  New-Report -EmailAddressList $EmailAddresses -Updates $Updates -OperatingSystem $OperatingSystem -Architecture $Architecture  
250:  Write-Host  
251:  Write-Host "Total Number of Updates:"$Updates.Count  
252:  $Filters = $null  
253:  $Updates = $null  
254:  $UpdateTypes = $null  
255:    
256:  #Remove Variables  
257:  Remove-Variable -Name Architecture -Scope Local -Force  
258:  Remove-Variable -Name EmailAddresses -Scope Local -Force  
259:  Remove-Variable -Name Filters -Scope Local -Force  
260:  Remove-Variable -Name LogFile -Scope Local -Force  
261:  Remove-Variable -Name Namespace -Scope Local -Force  
262:  Remove-Variable -Name OperatingSystem -Scope Local -Force  
263:  Remove-Variable -Name Updates -Scope Local -Force  
264:  Remove-Variable -Name UpdateTypes -Scope Local -Force  
265:    

08 December 2015

Windows Updates List

There is a newer tool located here


I have been working on writing a new script for SCCM and decided while writing it, I would take one of the functions and make it into a separate script for just retrieving windows updates. Sometimes you need a list to compare against, which is what I am using this for as a reporting tool in another script I am writing.

This script will query the SCCM server for a list of all Microsoft updates for a specific OS. The list can be customized down to a specific architecture, update types, such as security updates and service packs, and the list can filter out such things as IE 8, IE 9, and such.

The first thing is to customize the Namespace variable with your company's sitecode on line 21. Next, you will need to change line 28 to the OS you are wanting to search for. I put a couple of examples beside it, but you can use any OS that is in the All Software Updates list. On line 29, You can enter x86, x64, or null. Such OSs as 2012 R2 don't display a system architecture in the list, so you can use null. For UpdateTypes, you can enter the type of update you want to search for, such as Update or Security Update. If you leave the array blank, it will return all update types. Finally, $Filters lets you filter out updates that contain certain word in the title. I filtered out IE 8, 9, and 10, since my firm uses 11.

The script will then return a list of all updates and then a count of how many were returned.

NOTE: I ran this script from the SCCM server.

You can download this script from here.


WindowsUpdatesList.ps1
1:  <#       
2:       .NOTES  
3:       ===========================================================================  
4:        Created with:      SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.98  
5:        Created on:       12/8/2015 9:08 AM  
6:        Created by:       Mick Pletcher  
7:        Organization:         
8:        Filename:        WindowsUpdatesList.ps1  
9:       ===========================================================================  
10:       .DESCRIPTION  
11:            This script will generate a list of Windows updates from a query of the SCCM  
12:            server. You will need to customize the Namespace variable for your SCCM  
13:            server on line 19. Line 27 is where you input the OS you are searching for.  
14:            This can include any OS in the   
15:  #>  
16:    
17:  #Declare Variables  
18:  Set-Variable -Name Architecture -Force  
19:  Set-Variable -Name Filter -Force  
20:  Set-Variable -Name Filters -Force  
21:  Set-Variable -Name Namespace -Value root\sms\site_<sitecode> -Force  
22:  Set-Variable -Name OperatingSystem -Force  
23:  Set-Variable -Name Updates -Force  
24:  Set-Variable -Name UpdateType -Force  
25:  Set-Variable -Name UpdateTypes -Force  
26:    
27:  cls  
28:  $OperatingSystem = "Windows 7" #Windows 7, Windows 8.1, Windows Server 2012 R2  
29:  $Architecture = "x86" #x86, x64, or null  
30:  $UpdateTypes = @() #Security Update, Update, Service Pack  
31:  $Filters = @("Internet Explorer 8", "Internet Explorer 9", "Internet Explorer 10")  
32:    
33:  If ($Architecture -eq "x86") {  
34:       $Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) -and ($_.LocalizedDisplayName -notmatch "x64-based Systems") }  
35:  } elseif ($Architecture -eq "x64") {  
36:       $Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) -and ($_.LocalizedDisplayName -match "x64-based Systems") }  
37:  } else {  
38:       $Updates = Get-WmiObject -Class SMS_SoftwareUpdate -Namespace $Namespace | where-object { ($_.LocalizedDisplayName -match $OperatingSystem) }  
39:  }  
40:  foreach ($Filter in $Filters) {  
41:       $Updates = $Updates | where {$_.LocalizedDisplayName -notmatch $Filter}  
42:  }  
43:  If ($UpdateTypes.Count -ge 1) {  
44:       foreach ($UpdateType in $UpdateTypes) {  
45:            $Updates = $Updates | where { $_.LocalizedCategoryInstanceNames -match $UpdateType }  
46:       }  
47:       If ($UpdateTypes -eq "Update") {  
48:            $Updates = $Updates | where { $_.LocalizedDisplayName -notmatch "Security Update" }  
49:       }  
50:  }  
51:  $Updates.LocalizedDisplayName  
52:  Write-Host  
53:  Write-Host "Total Number of Updates:"$Updates.Count  
54:  $Filters = $null  
55:    
56:  #Remove Variables  
57:  Remove-Variable -Name Architecture -Force  
58:  Remove-Variable -Name Filter -Force  
59:  Remove-Variable -Name Filters -Force  
60:  Remove-Variable -Name Namespace -Force  
61:  Remove-Variable -Name OperatingSystem -Force  
62:  Remove-Variable -Name Updates -Force  
63:  Remove-Variable -Name UpdateType -Force  
64:  Remove-Variable -Name UpdateTypes -Force  
65:    

02 December 2015

Automating Microsoft Endpoint Full System Scan upon Infection with Email Notification

While helping to manage Microsoft Endpoint, a former colleague suggested that I setup Endpoint to automatically run a full system scan each time an infection is detected. I googled the blog posting on it and although it is a great post, I figured I could streamline it even more by just using SCCM alone to achieve the same outcome. It is nice when you are out of the office and your backup might not have the time to keep an eye on the antivirus infections.

This is a second edition of the previous script I wrote. I decided to leave that script if you do not want to have email notification upon a full system scan. This script includes sending out an email to the specified users in the EmailAddresses.txt file. This file resides in the same directory as the script. The other thing that needs to be done is to define the Installation program in SCCM using psexec.exe. Psexec.exe will also need to reside in the same directory as the PowerShell script. This allows the PowerShell script to be executed under a domain account, thereby giving it the ability to use the send-mailmessage commandlet.  Here is how to do this:

psexec.exe \\%computername% -u <domain>\<username> -p <password> -h cmd.exe /c "echo . | powershell.exe -executionpolicy bypass -file install.ps1"


I decided to use the SCCM custom application detection to scan a system and see if a full system scan has been performed. I first started out by writing a powershell script that would perform a WMI query on the SCCM server for the status of the system the application detection was being run on. The problem I ran across was that the application is being run under system credentials, which would require me to pass network credentials within the script. Instead of having to do this, I decided to query the event viewer logs on the local machine to look for the last infection date/time, which is event 1116. I queried all machines in my firm to find another event log that was unused, and 1118 happened to be just the one.

Here is how the process works:

  1. SCCM deploys the package to the system.
  2. The application detection queries the event viewer logs for the last 1116 ID (infection).
  3. The application detection queries the event viewer logs for the last 1118 ID.
  4. If a system 1118 ID  does not exist since the last infection, or there is no 1116 ID detected, the custom detection method will exit out as a failure.
  5. If the custom detection failed, the antivirusscan.ps1 file will be executed on the machine.
  6. An email is sent that tells a scan was performed on %COMPUTERNAME% with the virus details in the body.
  7. Once the scan is complete, a machine policy update is initiated to update the SCCM server with the status of the system.
  8. The application detection is initiated again to confirm the scan occurred. 


This is setup in SCCM as a normal application deployment. The only thing that differs from a standard deployment is the application detection method. That script is imported in for the detection method. The antivirusscan.ps1 file is setup as the installation program. I have mine entered like this:
powershell.exe -executionpolicy bypass -file antivirusscan.ps1

One more thing is that I have the application hidden from the software center. There really isn't a need for it to be there.

Line 57 on the AntivirusScanEmail.ps1 file is the only line of code you should have to customize.

You can download the application and application detection files from the following links:



AntivirusScanEmail.ps1
1:  <#       
2:       .NOTES  
3:       ===========================================================================  
4:        Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.98  
5:        Created on:       11/19/2015 3:26 PM  
6:        Created by:       Mick Pletcher  
7:        Organization:         
8:        Filename:        AntiVirusScanEmail.ps1  
9:       ===========================================================================  
10:       .DESCRIPTION  
11:            This script will initiate a full or quick scan, whichever one is uncommented  
12:            out below. It will then write a log to the event viewer logs showing the   
13:            scan was executed. Next, it will email the designated IT staff telling the   
14:            system scan has been performed. The final step is to execute a machine policy  
15:            update so the SCCM server is updated on the status of the system.  
16:  #>  
17:    
18:  #Declare Variables  
19:  Set-Variable -Name EmailAddress -Force  
20:  Set-Variable -Name EmailAddresses -Force  
21:  Set-Variable -Name LastInfection -Force  
22:  Set-Variable -Name Output -Force  
23:  Set-Variable -Name RelativePath -Force  
24:  Set-Variable -Name SMSwmi -Force  
25:  Set-Variable -Name strAction -Force  
26:  Set-Variable -Name Subject -Force  
27:  Set-Variable -Name WMIPath -Force  
28:    
29:  Import-Module $env:ProgramFiles"\Microsoft Security Client\MpProvider"  
30:  $RelativePath = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent) + "\"  
31:  $EmailAddresses = @()  
32:  $EmailAddresses = Get-Content -Path $RelativePath"EmailAddresses.txt"  
33:  $LastInfection = get-winevent -filterhashtable @{ logname = 'system'; ID = 1116 } -maxevents 1 -ErrorAction SilentlyContinue  
34:  <#Full Scan#>  
35:  Start-MProtScan -ScanType "FullScan"  
36:  cls  
37:  Write-Warning "Error: $_"  
38:  Write-Host $_.Exception.ErrorCode  
39:  New-EventLog –LogName System –Source "Antimalware Full Scan"  
40:  If ((Get-EventLog -LogName System -Source "Antimalware Quick Scan") -eq $null) {  
41:       New-EventLog –LogName System –Source "Antimalware Quick Scan"  
42:  }  
43:  Write-EventLog -LogName System -Source "Antimalware Full Scan" -EntryType Information -EventId 1118 -Message "Antimalware full system scan was performed" -Category ""  
44:  $Subject = "Virus Detection Report for" + [char]32 + $env:COMPUTERNAME  
45:  $Output = "An antimalware full system scan has been performed on" + [char]32 + $env:COMPUTERNAME + [char]32 + "due to the virus detection listed below." + [char]13 + [char]13 + $LastInfection.Message  
46:    
47:  <#Quick Scan  
48:  Start-MProtScan -ScanType "QuickScan"  
49:  If ((Get-EventLog -LogName System -Source "Antimalware Quick Scan") -eq $null) {  
50:       New-EventLog –LogName System –Source "Antimalware Quick Scan"  
51:  }  
52:  Write-EventLog -LogName System -Source "Antimalware Quick Scan" -EntryType Information -EventId 1118 -Message "Antimalware quick system scan was performed" -Category ""  
53:  $Subject = "Virus Detection Report for" + [char]32 + $env:COMPUTERNAME  
54:  $Output = "An antimalware quick system scan has been performed on" + [char]32 + $env:COMPUTERNAME + [char]32 + "due to the virus detection listed below." + [char]13 + [char]13 + $LastInfection.Message  
55:  #>  
56:  foreach ($EmailAddress in $EmailAddresses) {  
57:       Send-MailMessage -To $EmailAddress -From "IT@acme.com" -Subject $Subject -Body $Output -SmtpServer "smtp.acme.com"  
58:  }  
59:  $WMIPath = "\\" + $env:COMPUTERNAME + "\root\ccm:SMS_Client"  
60:  $SMSwmi = [wmiclass]$WMIPath  
61:  $strAction = "{00000000-0000-0000-0000-000000000021}"  
62:  [Void]$SMSwmi.TriggerSchedule($strAction)  
63:    
64:  #Cleanup Variables  
65:  Remove-Variable -Name EmailAddress -Force  
66:  Remove-Variable -Name EmailAddresses -Force  
67:  Remove-Variable -Name LastInfection -Force  
68:  Remove-Variable -Name Output -Force  
69:  Remove-Variable -Name RelativePath -Force  
70:  Remove-Variable -Name SMSwmi -Force  
71:  Remove-Variable -Name strAction -Force  
72:  Remove-Variable -Name Subject -Force  
73:  Remove-Variable -Name WMIPath -Force  
74:    


ApplicationVirusDetectionMethodEmail.ps1

1:  <#       
2:       .NOTES  
3:       ===========================================================================  
4:        Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.98  
5:        Created on:       11/19/2015 3:26 PM  
6:        Created by:       Mick Pletcher  
7:        Organization:         
8:        Filename:        ApplicationVirusDetectionMethodEmail.ps1  
9:       ===========================================================================  
10:       .DESCRIPTION  
11:  #>  
12:    
13:    
14:  $LastInfection = get-winevent -filterhashtable @{ logname = 'system'; ID = 1116 } -maxevents 1 -ErrorAction SilentlyContinue  
15:  $LastFullScan = get-winevent -filterhashtable @{ logname = 'system'; ID = 1118 } -maxevents 1 -ErrorAction SilentlyContinue  
16:  If (($LastFullScan.TimeCreated -lt $LastInfection.TimeCreated) -or ($LastInfection -eq $null)) {  
17:       Start-Sleep -Seconds 5  
18:       exit 0  
19:  } else {  
20:       Write-Host "No Infection"  
21:       Start-Sleep -Seconds 5  
22:       exit 0  
23:  }  
24: