Mick's IT Blogs

Mick's IT Blogs

Latest Updates

22 March 2017

PowerShell: Disable Cisco Jabber History

Posted By: Mick Pletcher - 3:49 PM















I published a blog posting on how to securely delete the Cisco Jabber conversation using the PowerShell script I had written. It occurred to me that the .DB file which contains the conversations could be prevented from recording in the first place. This is done by setting the .DB file to read-only. In order to do this, there is a specific process that needs to take place, especially if this is being done to systems where conversations have already taken place, otherwise you would have old conversations permanently left in the .DB file.

The .DB file needs to be deleted and then recreated before setting it to read-only. This process can only occur after a user is logged in because of the .DB file is stored within the user profile. Jabber is first closed out. Once closed, the .DB file is deleted. Jabber is then opened back up to recreate the .DB file. Jabber is once again closed. The .DB file is not set to read-only and Jabber is reopened once again.

After I fomulated this process, I used SAPIEN's PowerShell Studio to write the code. PowerShell Studio made writing this a breeze and as you can see in the code, it is very clean and well documented due to the app.

Here is a video clip of the script running on my own machine.


The script can be implemented through a package in SCCM or it can be setup to execute from a share as a run once registry entry when the user logs in the first time. SCCM is probably the best option as it does not execute the script immediately. It jabber has not been launched the first time before the script runs, the script will fail because of the .DB file will not be present. Another issue I encountered was executing the script. It must be executed in the 32-bit PowerShell. If executed in 64-Bit PowerShell, the add/remove programs lookup will fail.

You can download the script from my GitHub site located here.


 <#  
      .SYNOPSIS  
           Disable Cisco Jabber Chat History  
        
      .DESCRIPTION  
           This script will disable the Jabber chat history by setting the .DB file to read-only. It begins by killing the Jabber task, deleting the .DB file, reopening Jabber, and then setting the .DB file to read-only. The script uses this process because if the old .DB file has not been deleted before setting it to read-only, the stored conversations will be there permanently. Since the .DB file is stored in the user profile, this cannot be done in the build.  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.3.131  
           Created on:       03/21/2017 4:21 PM  
           Created by:       Mick Pletcher  
           Filename:         CiscoJabberChatCleanup.ps1  
           ===========================================================================  
 #>  
   
 [CmdletBinding()]  
 param ()  
   
 function Close-Process {  
 <#  
      .SYNOPSIS  
           Stop ProcessName  
        
      .DESCRIPTION  
           Kills a ProcessName and verifies it was stopped while reporting it back to the screen.  
        
      .PARAMETER ProcessName  
           Name of ProcessName to kill  
        
      .EXAMPLE  
           PS C:\> Close-ProcessName -ProcessName 'Value1'  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([boolean])]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$ProcessName  
      )  
        
      $Process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue  
      If ($Process -ne $null) {  
           $Output = "Stopping " + $Process.Name + " process....."  
           Stop-Process -Name $Process.Name -Force -ErrorAction SilentlyContinue  
           Start-Sleep -Seconds 1  
           $TestProcess = Get-Process $ProcessName -ErrorAction SilentlyContinue  
           If ($TestProcess -eq $null) {  
                $Output += "Success"  
                Write-Host $Output  
                Return $true  
           } else {  
                $Output += "Failed"  
                Write-Host $Output  
                Return $false  
           }  
      } else {  
           Return $true  
      }  
 }  
   
 function Get-RelativePath {  
 <#  
      .SYNOPSIS  
           Get the relative path  
        
      .DESCRIPTION  
           Returns the location of the currently running PowerShell script  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      $Path = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent) + "\"  
      Return $Path  
 }  
   
 function Open-Application {  
 <#  
      .SYNOPSIS  
           Open Application  
        
      .DESCRIPTION  
           Opens an applications  
        
      .PARAMETER Executable  
           A description of the Executable parameter.  
        
      .PARAMETER ApplicationName  
           Display Name of the application  
        
      .PARAMETER Process  
           Application Process Name  
        
      .EXAMPLE  
           PS C:\> Open-Application -Executable 'Value1'  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [string]$Executable,  
           [ValidateNotNullOrEmpty()][string]$ApplicationName  
      )  
        
      $Architecture = Get-Architecture  
      $Uninstall = Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"  
      If ($Architecture -eq "64-bit") {  
           $Uninstall += Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"  
      }  
      $InstallLocation = ($Uninstall | ForEach-Object { Get-ItemProperty $_.PsPath } | Where-Object { $_.DisplayName -eq $ApplicationName }).InstallLocation  
      If ($InstallLocation[$InstallLocation.Length - 1] -ne "\") {  
           $InstallLocation += "\"  
      }  
      $Process = ($Executable.Split("."))[0]  
      $Output = "Opening $ApplicationName....."  
      Start-Process -FilePath $InstallLocation$Executable -ErrorAction SilentlyContinue  
      Start-Sleep -Seconds 5  
      $NewProcess = Get-Process $Process -ErrorAction SilentlyContinue  
      If ($NewProcess -ne $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function Remove-ChatFiles {  
 <#  
      .SYNOPSIS  
           Delete Jabber Chat Files  
        
      .DESCRIPTION  
           Deletes Jabber chat files located at %USERNAME%\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History and verifies they were deleted  
        
      .EXAMPLE  
           PS C:\> Remove-ChatFiles  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      #Get Jabber Chat history files  
      $ChatHistoryFiles = Get-ChildItem -Path $env:USERPROFILE'\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History' -Filter *.db  
      If ($ChatHistoryFiles -ne $null) {  
           foreach ($File in $ChatHistoryFiles) {  
                $Output = "Deleting " + $File.Name + "....."  
                Remove-Item -Path $File.FullName -Force | Out-Null  
                If ((Test-Path $File.FullName) -eq $false) {  
                     $Output += "Success"  
                } else {  
                     $Output += "Failed"  
                }  
           }  
           Write-Output $Output  
      } else {  
           $Output = "No Chat History Present"  
           Write-Output $Output  
      }  
 }  
   
 function Remove-MyJabberFilesFolder {  
 <#  
      .SYNOPSIS  
           Delete MyJabberFiles Folder  
        
      .DESCRIPTION  
           Delete the MyJabberFiles folder stores under %USERNAME%\documents and verifies it was deleted.  
        
      .EXAMPLE  
           PS C:\> Remove-MyJabberFilesFolder  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $MyJabberFilesFolder = Get-Item $env:USERPROFILE'\Documents\MyJabberFiles' -ErrorAction SilentlyContinue  
      If ($MyJabberFilesFolder -ne $null) {  
           $Output = "Deleting " + $MyJabberFilesFolder.Name + "....."  
           Remove-Item -Path $MyJabberFilesFolder -Recurse -Force | Out-Null  
           If ((Test-Path $MyJabberFilesFolder.FullName) -eq $false) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
           }  
           Write-Output $Output  
      } else {  
           $Output = "No MyJabberFiles folder present"  
           Write-Output $Output  
      }  
 }  
   
 function Set-DBFilePermissions {  
 <#  
      .SYNOPSIS  
           Set .DB File Permission  
        
      .DESCRIPTION  
           Make the .DB file read-only  
        
      .EXAMPLE  
                     PS C:\> Set-DBFilePermissions  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      #Get list of chat history files  
      $ChatHistoryFiles = Get-ChildItem -Path $env:USERPROFILE'\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History' -Filter *.db  
      foreach ($File in $ChatHistoryFiles) {  
           #Set .DB file to read-only  
           $Output = "Setting " + $File.Name + " to Read-Only....."  
           $ReadOnly = Get-ItemPropertyValue -Path $File.FullName -Name IsReadOnly  
           If (($ReadOnly) -eq $false) {  
                Set-ItemProperty -Path $File.FullName -Name IsReadOnly -Value $true  
                $ReadOnly = Get-ItemPropertyValue -Path $File.FullName -Name IsReadOnly  
                If (($ReadOnly) -eq $true) {  
                     $Output += "Success"  
                } else {  
                     $Output += "Failed"  
                }  
           } else {  
                $Output += "Success"  
           }  
           Write-Output $Output  
      }  
 }  
   
 Clear-Host  
 #Kill Cisco Jabber Process  
 $JabberClosed = Close-Process -ProcessName CiscoJabber  
 #Delete .DB files from %USERNAME%\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History  
 Remove-ChatFiles  
 #Delete %USERNAME%\documents\MyJabberFiles directory  
 Remove-MyJabberFilesFolder  
 #Reopen Jabber if it was open  
 If ($JabberClosed -eq $true) {  
      Open-Application -ApplicationName "Cisco Jabber" -Executable CiscoJabber.exe  
 }  
 $JabberClosed = Close-Process -ProcessName CiscoJabber  
 #Set the .DB file to read-only  
 Set-DBFilePermissions  
 #Reopen Jabber  
 If ($JabberClosed -eq $true) {  
      Open-Application -ApplicationName "Cisco Jabber" -Executable CiscoJabber.exe  
 }  
   

16 March 2017

PowerShell: Generate User Logon Report

Posted By: Mick Pletcher - 4:26 PM















This script will generate a logon report of a specific user on a specific machine. This script is designed to query the event viewer logs on either a local or remote machine. It does not require WinRM for this to occur.

The script begins by querying the registry or remote registry to find the associated SID with the specified user profile. It then proceeds to retrieve all Event 4624 IDs from the event viewer logs. It filters those logs into four categories: Keyboard Logins, Unlock, Remote, and Cached Credentials. This website helped me considerably in knowing how to generate and classify the reporting.

The script will write the output to a CSV file, categorizing the logon times by the four categories listed above. If the -Rawdata parameter is used, the script will also write the detailed message data with a timestamp on each data entry to a TXT file.

Command line execution to get a formatted CSV file:

  • powershell.exe -file LogonTimes.ps1 -ComputerName "Test01" -Username "User01"
Command line execution to get a formatted CSV and raw data TXT file:
  • powershell.exe -file LogonTimes.ps1 -ComputerName "Test01" -Username "User01" -Rawdata
Command line execution to get a formatted CSV file on the local system:
  • powershell.exe -file LogonTimes.ps1 -Username "User01"
You can download the script from GitHub

PowerShell Studio made writing this script a breeze. If you look at the script and see all of the documentation in it, that is because PowerShell Studio makes that very easy and quick. It is well worth the money to purchase this tool. 

This is a view of a success execution of the script:


LogonTimes.ps1

 <#  
      .SYNOPSIS  
           User Logon Report  
        
      .DESCRIPTION  
           This script will query the event viewer logs of a specified system for a list of logon times for a specific user. There are four fields in the report: Keyboard logons, Screen Unlock, Remote Session logons, and Cached Logon. It has the option to either generate a report in a CSV file with all of the above field data, or it can generate a TXT file containing the raw message data with each data field split off by two dash rows.  
             
           NOTE: This does not require WinRM to be enabled to run on external systems. Also, this can take quite a while to execute if the logs are really big.  
        
      .PARAMETER ComputerName  
           Name of system to retrieve the logs from. If this is left blank, the script will use "." representing the computer this script is executing on.  
        
      .PARAMETER Rawdata  
           Generate a report using the raw data from the event viewer logs of the specified user  
        
      .PARAMETER Username  
           Username to generate this report of.  
        
      .EXAMPLE  
           Generate a CSV file report containing the times and sorted by each logon type  
           powershell.exe -file LogonTimes.ps1 -Username MickPletcher -ComputerName PC01  
             
           Generate a TXT file that contains all of the raw message data fields for the specified system  
           powershell.exe -file LogonTimes.ps1 -Username MickPletcher -ComputerName PC01 -Rawdata  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.136  
           Created on:       3/15/2017 12:00 PM  
           Created by:       Mick Pletcher  
           Filename:         LogonTimes.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [String]$ComputerName,  
      [switch]$Rawdata,  
      [ValidateNotNullOrEmpty()][string]$Username  
 )  
   
 function Get-FilteredData {  
 <#  
      .SYNOPSIS  
           Filter By LogonType Type  
        
      .DESCRIPTION  
           This will filter the data for the specified LogonType type  
        
      .PARAMETER LogonType  
           Specified LogonType type  
        
      .PARAMETER Message  
           Message to display on the screen  
        
      .PARAMETER Logons  
           Array containing all logons  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()]$LogonType,  
           [ValidateNotNullOrEmpty()][string]$Message,  
           [ValidateNotNullOrEmpty()]$Logons  
      )  
        
      $Errors = $false  
      Write-Host $Message"....." -NoNewline  
      Try {  
           $Data = $Logons | Where-Object { $_.Message -like "*Logon Type*"+[char]9+[char]9+$LogonType+"*" }  
      } catch {  
           $Errors = $true  
      }  
      If ($Errors -eq $false) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed" -ForegroundColor Red  
      }  
      Return $Data  
 }  
   
 function Get-SID {  
 <#  
      .SYNOPSIS  
           Retrieve SID from HKEY_LOCAL_MACHINE  
        
      .DESCRIPTION  
           This script will retrieve the SID by querying the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList by matching the ProfileImagePath value with the Username parameter.   
        
      .EXAMPLE  
           PS C:\> Get-SID  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      Write-Host "Retrieving SID for $Username....." -NoNewline  
      If ($ComputerName -eq ".") {  
           #Get associated SID of User Profile  
           $SID = (get-childitem -path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { $_.Name -like "*S-1-5-21*" } | ForEach-Object { Get-ItemProperty REGISTRY::$_ } | Where-Object { $_.ProfileImagePath -like "*$Username*" }).PSChildName  
      } else {  
           $HKEY_LOCAL_MACHINE = 2147483650  
           $Key = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"  
           $RegClass = Get-WMIObject -Namespace "Root\Default" -List -ComputerName $ComputerName | Where-object { $_.Name -eq "StdRegProv" }  
           $Value = "ProfileImagePath"  
           $SID = ($RegClass.EnumKey($HKEY_LOCAL_MACHINE, $Key)).sNames | Where-Object { $_ -like "*S-1-5-21*" } | ForEach-Object {  
                If (($RegClass.GetStringValue($HKEY_LOCAL_MACHINE, $Key + "\" + $_, $Value)).sValue -like "*" + $Username + "*") {  
                     $_  
                }  
           }  
      }  
      If (($SID -ne "") -and ($SID -ne $null)) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed" -ForegroundColor Red  
      }  
      Return $SID  
 }  
   
 function Get-RelativePath {  
 <#  
      .SYNOPSIS  
           Get the relative path  
        
      .DESCRIPTION  
           Returns the location of the currently running PowerShell script  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      $Path = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent) + "\"  
      Return $Path  
 }  
   
 function New-Report {  
 <#  
      .SYNOPSIS  
           Generate CSV Report File  
        
      .DESCRIPTION  
           This function will generate a CSV report.  
        
      .PARAMETER Keyboard  
           A description of the Keyboard parameter.  
        
      .PARAMETER Unlock  
           A description of the Unlock parameter.  
        
      .PARAMETER Remote  
           A description of the Remote parameter.  
        
      .PARAMETER Cached  
           A description of the Cached parameter.  
        
      .EXAMPLE  
                     PS C:\> New-Report  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           $Keyboard,  
           $Unlock,  
           $Remote,  
           $Cached  
      )  
        
      $RelativePath = Get-RelativePath  
      #Name of report file  
      $FileName = $RelativePath + "$Username.csv"  
      #Delete report file if it exists  
      If ((Test-Path $FileName) -eq $true) {  
           Write-Host "Deleting $Username.csv....." -NoNewline  
           Remove-Item -Path $FileName -Force  
           If ((Test-Path $FileName) -eq $false) {  
                Write-Host "Success" -ForegroundColor Yellow  
           } else {  
                Write-Host "Failed" -ForegroundColor Red  
           }  
      }  
      Write-Host "Generating $Username.csv report file....." -NoNewline  
      #Create new file  
      "Logon Type,Date/Time" | Out-File -FilePath $FileName -Encoding UTF8 -Force  
      $Errors = $false  
      #Report all keyboard logons  
      foreach ($Logon in $Keyboard) {  
           $Item = "Keyboard," + [string]$Logon.TimeCreated  
           try {  
                $Item | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           } catch {  
                $Errors = $true  
           }  
      }  
      #Report all screen unlocks  
      foreach ($Logon in $Unlock) {  
           $Item = "Unlock," + [string]$Logon.TimeCreated  
           Try {  
                $Item | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           } catch {  
                $Errors = $true  
           }  
      }  
      #Report all remote logons  
      foreach ($Logon in $Remote) {  
           $Item = "Remote," + [string]$Logon.TimeCreated  
           Try {  
                $Item | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           } catch {  
                $Errors = $true  
           }  
      }  
      #Report all cached logons  
      foreach ($Logon in $Cached) {  
           $Item = "Cached," + [string]$Logon.TimeCreated  
           Try {  
                $Item | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           } catch {  
                $Errors = $true  
           }  
      }  
      If ($Errors -eq $false) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed" -ForegroundColor Red  
      }  
 }  
   
 function Get-LogonLogs {  
 <#  
      .SYNOPSIS  
           Retrieve all Logon Logs from Event Viewer  
        
      .DESCRIPTION  
           This function will query the event viewer for all Event ID 4624, filtered with the user's SID.  
        
      .PARAMETER SID  
           User's SID  
        
      .EXAMPLE  
           PS C:\> Get-LogonLogs  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()]$SID  
      )  
        
      If ($ComputerName -ne ".") {  
           Write-Host "Retrieving all logon logs for $Username on $ComputerName....." -NoNewline  
      } else {  
           Write-Host "Retrieving all logon logs for $Username on $env:COMPUTERNAME....." -NoNewline  
      }  
      $Errors = $false  
      Try {  
           If ($ComputerName -ne ".") {  
                $AllLogons = Get-WinEvent -FilterHashtable @{ logname = 'security'; ID = 4624 } -ComputerName $ComputerName | where-object { ($_.properties.value -like "*$SID*") }  
           } else {  
                $AllLogons = Get-WinEvent -FilterHashtable @{ logname = 'security'; ID = 4624 } | where-object { ($_.properties.value -like "*$SID*") }  
           }  
      } catch {  
           $Errors = $true  
      }  
      If ($Errors -eq $false) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed" -ForegroundColor Red  
      }  
      Return $AllLogons  
 }  
   
 #******************************************************************************  
 #******************************************************************************  
   
 Clear-Host  
 If (($ComputerName -eq "") -or ($ComputerName -eq $null)) {  
      $ComputerName = "."  
 }  
 $SID = Get-SID  
 #Retrieve all logon logs  
 $AllLogons = Get-LogonLogs -SID $SID  
 #Logon at keyboard and screen of system  
 $KeyboardLogons = Get-FilteredData -Logons $AllLogons -LogonType "2" -Message "Filtering keyboard logons"  
 #Unlock workstation with password protected screen saver  
 $Unlock = Get-FilteredData -Logons $AllLogons -LogonType "7" -Message "Filtering system unlocks"  
 #Terminal Services, Remote Desktop or Remote Assistance  
 $Remote = Get-FilteredData -Logons $AllLogons -LogonType "10" -Message "Filtering remote accesses"  
 #logon with cached domain credentials such as when logging on to a laptop when away from the network  
 $CachedCredentials = Get-FilteredData -Logons $AllLogons -LogonType "11" -Message "Filtering cached logins"  
 #Generate a rawdata report  
 If ($Rawdata.IsPresent) {  
      $RelativePath = Get-RelativePath  
      #Name of report file  
      $FileName = $RelativePath + "$Username.txt"  
      #Delete report file if it exists  
      If ((Test-Path $FileName) -eq $true) {  
           Write-Host "Deleting $Username.txt....." -NoNewline  
           Remove-Item -Path $FileName -Force  
           If ((Test-Path $FileName) -eq $false) {  
                Write-Host "Success" -ForegroundColor Yellow  
           } else {  
                Write-Host "Failed" -ForegroundColor Red  
           }  
      }  
      Write-Host "Generating raw data file....." -NoNewline  
      foreach ($Logon in $AllLogons) {  
           [string]$Logon.TimeCreated | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           $Logon.Message | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           " " | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           "----------------------------------------------------------------------------------------------------------------------------------------------------------------" | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           "----------------------------------------------------------------------------------------------------------------------------------------------------------------" | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
           " " | Out-File -FilePath $FileName -Encoding UTF8 -Append -Force  
      }  
      If ((Test-Path $FileName) -eq $true) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed" -ForegroundColor Red  
      }  
 } else {  
      New-Report -Keyboard $KeyboardLogons -Unlock $Unlock -Remote $Remote -Cached $CachedCredentials  
 }  

06 March 2017

PowerShell: Uninstall MSI by Application Name

Posted By: Mick Pletcher - 3:14 PM















Here is a function that will uninstall an MSI installed application by the name of the app. You do not need to input the entire name either. For instance, say you are uninstalling all previous versions of Adobe Reader. Adobe Reader is always labeled Adobe Reader X, Adobe Reader XI, and so forth. This script allows you to do this without having to find out every version that is installed throughout a network and then enter an uninstaller line for each version. You just need to enter Adobe Reader as the application name and the desired switches. It will then search the name fields in the 32 and 64 bit uninstall registry keys to find the associated GUID. Finally, it will execute an msiexec.exe /x {GUID} to uninstall that version.

This is an update to the previous post on this. I dramatically improved the code to make this function much more efficient. 

NOTE: I used Sapien's PowerShell Studio to write this script that significantly simplified the process and made it a snap to write. I highly recommend this product for all PowerShell scripters!


 <#  
      .SYNOPSIS  
           Uninstall MSI by Application Name  
        
      .DESCRIPTION  
           Here is a function that will uninstall an MSI installed application by the name of the app. You do not need to input the entire name either. For instance, say you are uninstalling all previous versions of Adobe Reader. Adobe Reader is always labeled Adobe Reader X, Adobe Reader XI, and so forth. You just need to enter Adobe Reader as the application name and the desired switches. It will then search the name fields in the 32 and 64 bit uninstall registry keys to find the associated GUID. Finally, it will execute an msiexec.exe /x {GUID} to uninstall that version.  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.136  
           Created on:       3/6/2017 2:24 PM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:         UninstallMSIByName.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param ()  
   
 function Uninstall-MSIByName {  
 <#  
      .SYNOPSIS  
           Uninstall-MSIByName  
        
      .DESCRIPTION  
           Uninstalls an MSI application using the MSI file  
        
      .PARAMETER ApplicationName  
           Display Name of the application. This can be part of the name or all of it. By using the full name as displayed in Add/Remove programs, there is far less chance the function will find more than one instance.  
        
      .PARAMETER Switches  
           MSI switches to control the behavior of msiexec.exe when uninstalling the application.  
        
      .EXAMPLE  
           Uninstall-MSIByName "Adobe Reader" "/qb- /norestart"  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][String]$ApplicationName,  
           [ValidateNotNullOrEmpty()][String]$Switches  
      )  
        
      #MSIEXEC.EXE  
      $Executable = $Env:windir + "\system32\msiexec.exe"  
      #Get list of all Add/Remove Programs for 32-Bit and 64-Bit  
      $Uninstall = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -Recurse -ErrorAction SilentlyContinue  
      If (((Get-WmiObject -Class Win32_OperatingSystem | Select-Object OSArchitecture).OSArchitecture) -eq "64-Bit") {  
           $Uninstall += Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall -Recurse -ErrorAction SilentlyContinue  
      }  
      #Find the registry containing the application name specified in $ApplicationName  
      $Key = $uninstall | foreach-object { Get-ItemProperty REGISTRY::$_ } | where-object { $_.DisplayName -like "*$ApplicationName*" }  
      If ($Key -ne $null) {  
           Write-Host "Uninstall"$Key.DisplayName"....." -NoNewline  
           #Define msiexec.exe parameters to use with the uninstall  
           $Parameters = "/x " + $Key.PSChildName + [char]32 + $Switches  
           #Execute the uninstall of the MSI  
           $ErrCode = (Start-Process -FilePath $Executable -ArgumentList $Parameters -Wait -Passthru).ExitCode  
           #Return the success/failure to the display  
           If (($ErrCode -eq 0) -or ($ErrCode -eq 3010) -or ($ErrCode -eq 1605)) {  
                Write-Host "Success" -ForegroundColor Yellow  
           } else {  
                Write-Host "Failed with error code "$ErrCode -ForegroundColor Red  
           }  
      }  
 }  
   
 Clear-Host  
 Uninstall-MSIByName -ApplicationName "Cisco Jabber" -Switches "/qb- /norestart"  
   

28 February 2017

Bitlocker Recovery Password Utility

Posted By: Mick Pletcher - 1:20 PM















Recently, we encountered an issue where we found out a few systems did not have the BitLocker recovery password backed up to active directory. We have the GPO in place that pushes that key to AD, but for some reason, a few systems had gotten by without performing the backup.

I found out that during the build process, a few of those machines had been taken offline before the process had finished, therefore AD wasn't available to receive the encryption password. A couple of others had been accidentally decrypted and re-encrypted therefore the key in AD was no longer valid.

We do have the plan later this year after we deploy Windows 10 to go to MBAM, but before that happens, I wanted to make sure the BitLocker recovery passwords are uploaded to AD.

This script is designed to be run on PCs either one-time or a reoccurring basis. I wrote this script for admins that have SCCM and for those that do not. The script will query the local machine for the BitLocker recovery password. If -ActiveDirectory is selected, it will then query AD for the recovery password(s). If the password matches, nothing occurs. If the password does not match, the script will delete the password in AD and upload the new password. If AD contains the correct password, but there are others also present, the script will delete the other passwords, thereby leaving the correct one in AD.

I have also added a -SCCMReporting parameter if you want to 1) report to SCCM if the recovery password is backed up (boolean value), and 2) if you want the recovery password also reported to SCCM.

For those admins with a simple network setup without SCCM and AD, I have included the -NetworkShare option that will create a file <computername>.txt on the specified network share -NetworkSharePath with the BitLocker password contained within the text file. This method could also be used as a backup to AD if preferred.

NOTE: If you are using this script with active directory, you will need remote server administration toolkit (RSAT) installed on you local machines. The script requires the activedirectory module. One more thing. I cannot stress enough to make absolutely sure this script is functioning correctly on your network. Just because it works on the network this script was written on does not guarantee it will work on another network. You must have PowerShell knowledge to use this script and modify it if needed for your environment. If it does not work correctly on your environment, it could potentially remove good passwords from AD. 

The ideal way to deploy this script is to set it up as a package in SCCM. I have mine configured to run every day at noon time in order to get the maximum number of systems. You could also set this up as a scheduled task.

Here are examples of using the script:
  • Backup recovery password to active directory
    • powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory
  • Backup recovery password to active directory and SCCM
    • powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory -SCCMReporting -SCCMBitlockerPassword
  • Backup recovery password to active directory and report AD backup status to SCCM
    • powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory -SCCMReporting
  • Backup recovery password to network share
    • powershell.exe -file BitlockerRecoveryKey.ps1 -NetworkShare -NetworkSharePath "\\UNC Path\Directory"
This is the best I can do for a screenshot, as a video would expose my BitLocker recovery password. This shows the script being executed and reporting back to SCCM. 


I would like to say thanks to Stephane van Gulick for his Get-BitLockerRecoveryKeyId function that made the rest of this script possible. 

A huge thank you to SAPIEN technologies for PowerShell Studio that made this script a breeze to write. It also helped make this script easy to document for other users to better understand. 



You can download the script from here



 <#  
      .SYNOPSIS  
           Bitlocker Recovery Key  
        
      .DESCRIPTION  
           This script gives the ability to backup the bitlocker recovery key to active directory, SCCM, and/or a network share. If AD is selected, it will query active directory for the latest bitlocker recovery key. Next, it will retrieve the bitlocker recovery key from the local system and then compare the keys to make sure it is backed up to active directory. If SCCM is selected, it will publish the status if the key is backed up to AD and if -SCCMBitlocker Password is selected, it will backup that password to SCCM. It can also backup to a network share if -NetworkShare is selected for admins that do not have SCCM.   
        
      .PARAMETER ActiveDirectory  
           Select this to specify the backing up the recovery password to active directory  
        
      .PARAMETER NetworkShare  
           Specifies to create a text file (<Computer Name>.txt) on the network share specified in parameter -NetworkSharePath. -NetworkShare is intended for admins who do not have SCCM.  
        
      .PARAMETER NetworkSharePath  
           UNC path where to store the text files containing the bitlocker recovery keys.  
        
      .PARAMETER SCCMBitlockerPassword  
           Select this switch if you want the bitlocker password reported to SCCM  
        
      .PARAMETER SCCMReporting  
           Report bitlocker recovery key to SCCM  
        
      .EXAMPLE  
           Backup recovery password to active directory  
                powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory  
   
           Backup recovery password to active directory and SCCM  
                powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory -SCCMReporting -SCCMBitlockerPassword  
   
           Backup recovery password to active directory and report AD backup status to SCCM  
                powershell.exe -file BitlockerRecoveryKey.ps1 -ActiveDirectory -SCCMReporting  
   
           Backup recovery password to network share  
                powershell.exe -file BitlockerRecoveryKey.ps1 -NetworkShare -NetworkSharePath "\\UNC Path\Directory"  
   
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.129  
           Created on:       11/14/2016 1:18 PM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:         BitlockerRecoveryKey.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [switch]$ActiveDirectory,  
      [switch]$NetworkShare,  
      [string]$NetworkSharePath,  
      [switch]$SCCMBitlockerPassword,  
      [switch]$SCCMReporting  
 )  
 Import-Module ActiveDirectory  
   
 Function Get-BitLockerRecoveryKeyId {  
        
      <#  
      .SYNOPSIS  
      This returns the Bitlocker key protector id.  
        
      .DESCRIPTION  
      The key protectorID is retrived either according to the protector type, or simply all of them.  
        
      .PARAMETER KeyProtectorType  
        
      The key protector type can have one of the following values :  
      *TPM  
      *ExternalKey  
      *NumericPassword  
      *TPMAndPin  
      *TPMAndStartUpdKey  
      *TPMAndPinAndStartUpKey  
      *PublicKey  
      *PassPhrase  
      *TpmCertificate  
      *SID  
        
        
      .EXAMPLE  
        
      Get-BitLockerRecoveryKeyId  
      Returns all the ID's available from all the different protectors.  
   
   .EXAMPLE  
   
     Get-BitLockerRecoveryKeyId -KeyProtectorType NumericPassword  
     Returns the ID(s) of type NumericPassword  
   
   
      .NOTES  
           Version: 1.0  
     Author: Stephane van Gulick  
     Creation date:12.08.2014  
     Last modification date: 12.08.2014  
   
      .LINK  
           www.powershellDistrict.com  
   
      .LINK  
           http://social.technet.microsoft.com/profile/st%C3%A9phane%20vg/  
   
   .LINK  
     #http://msdn.microsoft.com/en-us/library/windows/desktop/aa376441(v=vs.85).aspx  
 #>       
        
      [cmdletBinding()]  
      Param (  
                [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][ValidateSet("Alltypes", "TPM", "ExternalKey", "NumericPassword", "TPMAndPin", "TPMAndStartUpdKey", "TPMAndPinAndStartUpKey", "PublicKey", "PassPhrase", "TpmCertificate", "SID")]$KeyProtectorType  
      )  
        
      $BitLocker = Get-WmiObject -Namespace "Root\cimv2\Security\MicrosoftVolumeEncryption" -Class "Win32_EncryptableVolume"  
      switch ($KeyProtectorType) {  
           ("Alltypes") { $Value = "0" }  
           ("TPM") { $Value = "1" }  
           ("ExternalKey") { $Value = "2" }  
           ("NumericPassword") { $Value = "3" }  
           ("TPMAndPin") { $Value = "4" }  
           ("TPMAndStartUpdKey") { $Value = "5" }  
           ("TPMAndPinAndStartUpKey") { $Value = "6" }  
           ("PublicKey") { $Value = "7" }  
           ("PassPhrase") { $Value = "8" }  
           ("TpmCertificate") { $Value = "9" }  
           ("SID") { $Value = "10" }  
           default { $Value = "0" }  
      }  
      $Ids = $BitLocker.GetKeyProtectors($Value).volumekeyprotectorID  
      return $ids  
 }  
   
 function Get-ADBitlockerRecoveryKeys {  
 <#  
      .SYNOPSIS  
           Retrieve Active Directory Recovery Keys  
        
      .DESCRIPTION  
           Get a list of all bitlocker recovery keys in active directory.  
        
      .EXAMPLE  
           PS C:\> Get-ADBitlockerRecoveryKeys  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      #Get Active Directory computer information  
      $ComputerName = $env:COMPUTERNAME  
      $ADComputer = Get-ADComputer -Filter { Name -eq $ComputerName }  
      #Get Bitlocker recovery keys  
      $ADBitLockerRecoveryKeys = Get-ADObject -Filter { objectclass -eq 'msFVE-RecoveryInformation' } -SearchBase $ADComputer.DistinguishedName -Properties 'msFVE-RecoveryPassword'  
      Return $ADBitLockerRecoveryKeys  
 }  
   
 function Get-BitlockerPassword {  
 <#  
      .SYNOPSIS  
           Get Bitlocker Password  
        
      .DESCRIPTION  
           Retrieve the bitlocker password of the specified protector ID  
        
      .PARAMETER ProtectorID  
           Key protector ID  
        
      .EXAMPLE  
           PS C:\> Get-BitlockerPassword -ProtectorID 'Value1'  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$ProtectorID  
      )  
        
      $Password = manage-bde -protectors -get ($env:ProgramFiles).split("\")[0] -id $ProtectorID | Where-Object { $_.trim() -ne "" }  
      $Password = $Password[$Password.Length - 1].Trim()  
      Return $Password  
 }  
   
 function Initialize-HardwareInventory {  
 <#  
      .SYNOPSIS  
           Perform Hardware Inventory  
        
      .DESCRIPTION  
           Perform a hardware inventory via the SCCM client to report the WMI entry.  
        
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $Output = "Initiate SCCM Hardware Inventory....."  
      $SMSCli = [wmiclass] "\\localhost\root\ccm:SMS_Client"  
      $ErrCode = ($SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000001}")).ReturnValue  
      If ($ErrCode -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function Invoke-ADBitlockerRecoveryPasswordCleanup {  
 <#  
      .SYNOPSIS  
           Cleanup Active Directory Bitlocker Recovery Passwords  
        
      .DESCRIPTION  
           This function will cleanup bitlocker recovery passwords that are no longer valid.  
        
      .PARAMETER LocalPassword  
           Bitlocker password of the local machine  
        
      .PARAMETER ADPassword  
           Bitlocker Passwords stored in active directory  
        
      .EXAMPLE  
           PS C:\> Invoke-ADBitlockerRecoveryPasswordCleanup  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$LocalPassword,  
           [ValidateNotNullOrEmpty()]$ADPassword  
      )  
        
      foreach ($Password in $ADPassword) {  
           If ($LocalPassword -ne $Password.'msFVE-RecoveryPassword') {  
                Remove-ADObject -Identity $Password.DistinguishedName -Confirm:$false  
           }  
      }  
 }  
   
 function Invoke-EXE {  
 <#  
      .SYNOPSIS  
           Execute the executable  
        
      .DESCRIPTION  
           Execute the executable  
        
      .PARAMETER DisplayName  
           A description of the DisplayName parameter.  
        
      .PARAMETER Executable  
           A description of the Executable parameter.  
        
      .PARAMETER Switches  
           A description of the Switches parameter.  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [String]$DisplayName,  
           [String]$Executable,  
           [String]$Switches  
      )  
        
      Write-Host "Uploading"$DisplayName"....." -NoNewline  
      #Test if executable is present  
      If ((Test-Path $Executable) -eq $true) {  
           #Execute the executable  
           $ErrCode = (Start-Process -FilePath $Executable -ArgumentList $Switches -Wait -Passthru).ExitCode  
      } else {  
           $ErrCode = 1  
      }  
      If (($ErrCode -eq 0) -or ($ErrCode -eq 3010)) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed with error code "$ErrCode -ForegroundColor Red  
      }  
 }  
   
 function New-WMIClass {  
 <#  
      .SYNOPSIS  
           Create New WMI Class  
        
      .DESCRIPTION  
           This will delete the specified WMI class if it already exists and create/recreate the class.  
        
      .PARAMETER Class  
           A description of the Class parameter.  
        
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If (($WMITest -ne "") -and ($WMITest -ne $null)) {  
           $Output = "Deleting " + $Class + " WMI class....."  
           Remove-WmiObject $Class  
           $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
           If ($WMITest -eq $null) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
                Exit 1  
           }  
           Write-Output $Output  
      }  
      $Output = "Creating " + $Class + " WMI class....."  
      $newClass = New-Object System.Management.ManagementClass("root\cimv2", [string]::Empty, $null);  
      $newClass["__CLASS"] = $Class;  
      $newClass.Qualifiers.Add("Static", $true)  
      $newClass.Properties.Add("ADBackup", [System.Management.CimType]::Boolean, $false)  
      $newClass.Properties["ADBackup"].Qualifiers.Add("key", $true)  
      $newClass.Properties["ADBackup"].Qualifiers.Add("read", $true)  
      $newClass.Properties.Add("RecoveryPassword", [System.Management.CimType]::string, $false)  
      $newClass.Properties["RecoveryPassword"].Qualifiers.Add("key", $true)  
      $newClass.Properties["RecoveryPassword"].Qualifiers.Add("read", $true)  
      $newClass.Put() | Out-Null  
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If ($WMITest -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
           Exit 1  
      }  
      Write-Output $Output  
 }  
   
 function New-WMIInstance {  
 <#  
      .SYNOPSIS  
           Write new instance  
        
      .DESCRIPTION  
           Write a new instance reporting the last time the system was rebooted  
        
      .PARAMETER ADBackup  
           Boolean value specifying if the bitlocker recovery key is backed up to active directory  
        
      .PARAMETER Class  
           WMI Class  
        
      .PARAMETER RecoveryPassword  
           Bitlocker recovery password  
        
      .PARAMETER LastRebootTime  
           Date/time the system was last rebooted  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][boolean]$ADBackup,  
           [ValidateNotNullOrEmpty()][string]$Class,  
           [ValidateNotNullOrEmpty()][string]$RecoveryPassword  
      )  
        
      $Output = "Writing Bitlocker instance to" + [char]32 + $Class + [char]32 + "class....."  
      $Return = Set-WmiInstance -Class $Class -Arguments @{ ADBackup = $ADBackup; RecoveryPassword = $RecoveryPassword }  
      If ($Return -like "*" + $ADBackup + "*") {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function Publish-RecoveryPasswordToActiveDirectory {  
 <#  
      .SYNOPSIS  
           Publish Bitlocker Recovery Password  
        
      .DESCRIPTION  
           Publish Bitlocker recovery password to active directory.  
        
      .PARAMETER BitlockerID  
           Bitlocker Recovery ID that contains the Bitlocker recovery password  
        
      .EXAMPLE  
           PS C:\> Publish-RecoveryPasswordToActiveDirectory  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$BitlockerID  
      )  
        
      #Define location of manage-bde.exe  
      $ManageBDE = $env:windir + "\System32\manage-bde.exe"  
      #Define the ManageBDE parameters to backup the Bitlocker recovery password to  
      $Switches = "-protectors -adbackup" + [char]32 + ($env:ProgramFiles).split("\")[0] + [char]32 + "-id" + [char]32 + $BitlockerID  
      Invoke-EXE -DisplayName "Backup Recovery Key to AD" -Executable $ManageBDE -Switches $Switches  
 }  
   
 function Remove-WMIClass {  
 <#  
      .SYNOPSIS  
           Delete WMIClass  
        
      .DESCRIPTION  
           Delete the WMI class from system  
        
      .PARAMETER Class  
           Name of WMI class to delete  
        
      .EXAMPLE  
                     PS C:\> Remove-WMIClass  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If (($WMITest -ne "") -and ($WMITest -ne $null)) {  
           $Output = "Deleting " + $Class + " WMI class....."  
           Remove-WmiObject $Class  
           $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
           If ($WMITest -eq $null) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
                Exit 1  
           }  
           Write-Output $Output  
      }  
 }  
   
 Clear-Host  
 #Retrieve numerical password ID  
 [string]$BitlockerID = Get-BitLockerRecoveryKeyId -KeyProtectorType NumericPassword  
 #Retrieve Bitlocker recovery password from the local system  
 [string]$BitlockerPassword = Get-BitlockerPassword -ProtectorID $BitlockerID  
 #Backup bitlocker password to active directory is parameter is selected  
 If ($ActiveDirectory.IsPresent) {  
      #Retrieve the bitlocker recovery password(s) from active directory  
      $ADBitlockerPassword = Get-ADBitlockerRecoveryKeys  
      #Check if bitlocker password exists. If not, push to active directory  
      If ($ADBitlockerPassword -ne $null) {  
           #Check if it is a single password which the AD backup does not match the password on the system, or an array of passwords  
           If ((($ADBitlockerPassword -is [Microsoft.ActiveDirectory.Management.ADObject]) -and ($ADBitlockerPassword.'msFVE-RecoveryPassword' -ne $BitlockerPassword)) -or ($ADBitlockerPassword -isnot [Microsoft.ActiveDirectory.Management.ADObject])) {  
                #Delete all bitlocker recovery passwords that do not match the password on the local machine  
                Invoke-ADBitlockerRecoveryPasswordCleanup -LocalPassword $BitlockerPassword -ADPassword $ADBitlockerPassword  
                #Get the password stored in AD after the cleanup  
                $ADBitlockerPassword = Get-ADBitlockerRecoveryKeys  
                #If the AD password does not exist, or does not match the local password, publish the new AD Bitlocker password  
                If (($ADBitlockerPassword.'msFVE-RecoveryPassword' -ne $BitlockerPassword) -or ($ADBitlockerPassword -eq $null)) {  
                     #Push the local bitlocker password to AD  
                     Publish-RecoveryPasswordToActiveDirectory -BitlockerID $BitlockerID  
                     #Retrieve the bitlocker recovery password from active directory  
                     $ADBitlockerPassword = $null  
                     $Count = 1  
                     #Wait until the bitlocker password is in active directory  
                     Do {  
                          $ADBitlockerPassword = Get-ADBitlockerRecoveryKeys  
                          Start-Sleep -Seconds 1  
                          $Count += 1  
                     } while (($ADBitlockerPassword -eq $null) -or ($Count -lt 30))  
                }  
           }  
      } else {  
           Publish-RecoveryPasswordToActiveDirectory -BitlockerID $BitlockerID  
           #Retrieve the bitlocker recovery password from active directory  
           $ADBitlockerPassword = $null  
           $Count = 1  
           #Wait until the bitlocker password is in active directory  
           Do {  
                $ADBitlockerPassword = Get-ADBitlockerRecoveryKeys  
                Start-Sleep -Seconds 1  
                $Count += 1  
           } while (($ADBitlockerPassword -eq $null) -and ($Count -lt 30))  
      }  
 }  
 #Publish data to SCCM  
 If ($SCCMReporting.IsPresent) {  
      New-WMIClass -Class Bitlocker_Reporting  
      If ($ADBitlockerPassword.'msFVE-RecoveryPassword' -eq $BitlockerPassword) {  
           If ($SCCMBitlockerPassword.IsPresent) {  
                New-WMIInstance -ADBackup $true -Class Bitlocker_Reporting -RecoveryPassword $BitlockerPassword  
           } else {  
                New-WMIInstance -ADBackup $true -Class Bitlocker_Reporting -RecoveryPassword " "  
           }  
      } else {  
           If ($SCCMBitlockerPassword.IsPresent) {  
                New-WMIInstance -ADBackup $false -Class Bitlocker_Reporting -RecoveryPassword $BitlockerPassword  
           } else {  
                New-WMIInstance -ADBackup $false -Class Bitlocker_Reporting -RecoveryPassword " "  
           }  
      }  
      #Initialize SCCM hardware inventory to force a reporting of the Bitlocker_Reporting class to SCCM  
      Initialize-HardwareInventory  
 } else {  
      Remove-WMIClass -Class Bitlocker_Reporting  
 }  
 #Publish data to Network Share  
 If ($NetworkShare.IsPresent) {  
      #Test if the $NetworkSharePath is defined and available  
      If ((Test-Path $NetworkSharePath) -eq $true) {  
           #Define the file to write the recovery key to  
           If ($NetworkSharePath[$NetworkSharePath.Length - 1] -ne "\") {  
                $File = $NetworkSharePath + "\" + $env:COMPUTERNAME + ".txt"  
           } else {  
                $File = $NetworkSharePath + $env:COMPUTERNAME + ".txt"  
           }  
           #Delete the file containing the recovery key if it exists  
           If ((Test-Path $File) -eq $true) {  
                $Output = "Deleting $env:COMPUTERNAME.txt file....."  
                Remove-Item -Path $File -Force  
                If ((Test-Path $File) -eq $false) {  
                     $Output += "Success"  
                } else {  
                     $Output += "Failed"  
                }  
                Write-Output $Output  
           }  
           #Create new text file  
           If ((Test-Path $File) -eq $false) {  
                $Output = "Creating $env:COMPUTERNAME.txt file....."  
                New-Item -Path $File -ItemType File -Force | Out-Null  
                If ((Test-Path $File) -eq $true) {  
                     Add-Content -Path $File -Value $BitlockerPassword  
                     $Output += "Success"  
                } else {  
                     $Output += "Failed"  
                }  
                Write-Output $Output  
           }  
      }  
 }  
 #Display output to the screen  
 Write-Output " "  
 $Output = "         Bitlocker ID: " + $BitlockerID  
 Write-Output $Output  
 $Output = "  Bitlocker Recovery Password: " + $BitlockerPassword  
 Write-Output $Output  
 $Output = "AD Bitlocker Recovery Password: " + $ADBitlockerPassword.'msFVE-RecoveryPassword' + [char]13  
 Write-Output $Output  
   

22 February 2017

Clearing Specific Print Queues

Posted By: Mick Pletcher - 2:48 PM














In a recent deployment, we ran into an issue where there had been print jobs stuck in the print que on some machines. We thought we had it fixed by running the following cmdlet:

Get-WmiObject Win32_Printer | where-object { $_.Name -like "*Workshare*" } | foreach-object { $_.CancelAllJobs() }

It worked on some machines, but others were not clearing. We did not want to delete print jobs to other printers. We had to find an alternative method to clear the jobs out. The script below was written to look at jobs in the %System32%\spool\printers directory. It will get a list of .SHD files. It will then open up the file and read the contents, filtering out everything except for alphabetical letters and then converting them to ASCII. Next, it searches the converted text for a partial or full name of the printer specified in the parameters, and marks it to be deleted. The script will then stop the print spooler, delete the files, and then restart the spooler. This script resolved our issue for making sure the specific printer was cleared of any print jobs. 

You can download the script from here.


 <#  
      .SYNOPSIS  
           Delete Print Jobs for Specific Printer  
        
      .DESCRIPTION  
           This script will delete print jobs for a specific printer. It gets a list of print jobs in the %SYSTEM32\Spool\PRINTERS directory. It reads the contents of the .SHD files, which have the names of the printer inside them. It then filters out those jobs that are not queued for the specified printer and deletes them. It stops the spooler before the deletion and then restarts it.   
        
      .PARAMETER PrinterName  
           Full or partial name of the printer to filter for  
        
      .EXAMPLE  
           Delete all printer jobs for printer named Workshare  
                powershell.exe -file ClearPrintSpooler.ps1 -PrinterName "Workshare"  
   
      .NOTES  
           ===========================================================================  
           Created with:      SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135  
           Created on:       2/22/2017 10:46 AM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:          ClearPrintSpooler.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [ValidateNotNullOrEmpty()][string]$PrinterName  
 )  
   
 Clear-Host  
 #Get list of print jobs  
 $Files = Get-ChildItem -Path $env:windir"\system32\spool\printers" -Filter *.SHD  
 #Initialize variable to contain list of files to delete  
 $DeleteFiles = @()  
 foreach ($File in $Files) {  
      #Read contents of binary file  
      $Contents = [System.IO.File]::ReadAllBytes($File.FullName)  
      #Filter out all contents that are not A-Z and a-z in the ASCII number fields  
      $Contents = $Contents | Where-Object { (($_ -ge 65) -and ($_ -le 90)) -or (($_ -ge 97) -and ($_ -le 122)) }  
      #Convert string to ASCII  
      foreach ($Value in $Contents) {  
           $Output += [char]$Value  
      }  
      #Add base file name to the $DeleteFiles list if the $PrinterName is in the converted string  
      If ($Output -like "*$PrinterName*") {  
           $DeleteFiles += $File.BaseName  
      }  
 }  
 #Delete all files that met the searched criteria  
 foreach ($File in $DeleteFiles) {  
      #Stop Print Spooler Service  
      Stop-Service -Name Spooler -Force | Out-Null  
      #Create Filter to search for files  
      $FileFilter = $File + ".*"  
      #Get list of files  
      $Filenames = Get-ChildItem -Path $env:windir"\system32\spool\printers" -Filter $FileFilter  
      #Delete each file  
      foreach ($Filename in $Filenames) {  
           Remove-Item -Path $Filename.FullName -Force | Out-Null  
      }  
      #Start Print Spooler Service  
      Start-Service -Name Spooler | Out-Null  
 }  
   

20 February 2017

Cisco Jabber Conversation Secure Delete Cleanup

Posted By: Mick Pletcher - 12:59 PM















Here is a script that will delete Cisco Jabber conversations. If you are in an environment where you do not want these conversations to be saved and recoverable, this tool with take care of it.

I wrote this tool so that it will kill the CiscoJabber process first and then deletes the appropriate file that stores the conversation. It will then restart Jabber. We set this up to execute when a user logs on and logs off. We have the script setup to make three passes of deletion.

We chose to use SDelete after reading this article on how much better SDelete is at cleaning up files on both SSD and HDD drives. You can download SDelete from here. The script is setup to execute SDelete.exe when it resides in the same location as the script.

Here is a video I took of the script executing. You can see the script closes jabber, deletes the associated .DB file, and then reopens Jabber. It must close Jabber in order to unlock the .DB file for deletion.



I have included examples of executing the script in the script documentation. As you can see in the script, I have set the SecureDeletePasses to 3, which can either be changed or overridden by defining it in the parameter at the time the script is executed.

One more thing about this script was how easy SAPIEN's PowerShell Studio made writing this script. PowerShell Studio takes your script writing abilities to another level as you can see in mine below.

You can download the script from here.


 <#  
      .SYNOPSIS  
           Delete Cisco Jabber Chat History  
        
      .DESCRIPTION  
           Deletes the files and folder that contain the Cisco Jabber chat history  
        
      .PARAMETER SecureDelete  
           Implement Secure Deletion of files and folders  
        
      .PARAMETER SecureDeletePasses  
           Number of secure delete passes  
        
      .EXAMPLE  
           Delete Cisco Jabber chat without secure delete  
                powershell.exe -file CiscoJabberChatCleanup.ps1  
   
           Delete Cisco Jabber chate with secure delete  
                powershell.exe -file CiscoJabberChatCleanup.ps1 -SecureDelete -SecureDeletePasses 3  
   
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.3.131  
           Created on:       12/13/2016 12:20 PM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:         CiscoJabberChatCleanup.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [switch]$SecureDelete,  
      [string]$SecureDeletePasses = '3'  
 )  
   
 function Close-Process {  
 <#  
      .SYNOPSIS  
           Stop ProcessName  
        
      .DESCRIPTION  
           Kills a ProcessName and verifies it was stopped while reporting it back to the screen.  
        
      .PARAMETER ProcessName  
           Name of ProcessName to kill  
        
      .EXAMPLE  
           PS C:\> Close-ProcessName -ProcessName 'Value1'  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([boolean])]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$ProcessName  
      )  
        
      $Process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue  
      If ($Process -ne $null) {  
           $Output = "Stopping " + $Process.Name + " process....."  
           Stop-Process -Name $Process.Name -Force -ErrorAction SilentlyContinue  
           Start-Sleep -Seconds 1  
           $TestProcess = Get-Process $ProcessName -ErrorAction SilentlyContinue  
           If ($TestProcess -eq $null) {  
                $Output += "Success"  
                Write-Host $Output  
                Return $true  
           } else {  
                $Output += "Failed"  
                Write-Host $Output  
                Return $false  
           }  
      } else {  
           Return $true  
      }  
 }  
   
 function Get-Architecture {  
 <#  
      .SYNOPSIS  
           Get-Architecture  
        
      .DESCRIPTION  
           Returns whether the system architecture is 32-bit or 64-bit  
        
      .EXAMPLE  
           Get-Architecture  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      $OSArchitecture = Get-WmiObject -Class Win32_OperatingSystem | Select-Object OSArchitecture  
      $OSArchitecture = $OSArchitecture.OSArchitecture  
      Return $OSArchitecture  
      #Returns 32-bit or 64-bit  
 }  
   
 function Get-RelativePath {  
 <#  
      .SYNOPSIS  
           Get the relative path  
        
      .DESCRIPTION  
           Returns the location of the currently running PowerShell script  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      $Path = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent) + "\"  
      Return $Path  
 }  
   
 function Open-Application {  
 <#  
      .SYNOPSIS  
           Open Application  
        
      .DESCRIPTION  
           Opens an applications  
        
      .PARAMETER Executable  
           A description of the Executable parameter.  
        
      .PARAMETER ApplicationName  
           Display Name of the application  
        
      .PARAMETER Process  
           Application Process Name  
        
      .EXAMPLE  
           PS C:\> Open-Application -Executable 'Value1'  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [string]$Executable,  
           [ValidateNotNullOrEmpty()][string]$ApplicationName  
      )  
        
      $Architecture = Get-Architecture  
      $Uninstall = Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"  
      If ($Architecture -eq "64-bit") {  
           $Uninstall += Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"  
      }  
      $InstallLocation = ($Uninstall | ForEach-Object {     Get-ItemProperty $_.PsPath } | Where-Object { $_.DisplayName -eq $ApplicationName }).InstallLocation  
      If ($InstallLocation[$InstallLocation.Length - 1] -ne "\") {  
           $InstallLocation += "\"  
      }  
      $Process = ($Executable.Split("."))[0]  
      $Output = "Opening $ApplicationName....."  
      Start-Process -FilePath $InstallLocation$Executable -ErrorAction SilentlyContinue  
      Start-Sleep -Seconds 5  
      $NewProcess = Get-Process $Process -ErrorAction SilentlyContinue  
      If ($NewProcess -ne $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function Remove-ChatFiles {  
 <#  
      .SYNOPSIS  
           Delete Jabber Chat Files  
        
      .DESCRIPTION  
           Deletes Jabber chat files located at %USERNAME%\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History and verifies they were deleted  
        
      .EXAMPLE  
           PS C:\> Remove-ChatFiles  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      #$JabberChatHistory = $env:USERPROFILE + '\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History'  
      #Get Jabber Chat history files  
      $ChatHistoryFiles = Get-ChildItem -Path $env:USERPROFILE'\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History' -Filter *.db  
      If ($ChatHistoryFiles -ne $null) {  
           foreach ($File in $ChatHistoryFiles) {  
                $Output = "Deleting " + $File.Name + "....."  
                If ($SecureDelete.IsPresent) {  
                     $RelativePath = Get-RelativePath  
                     $Architecture = Get-Architecture  
                     If ($Architecture -eq "32-bit") {  
                          $sDelete = [char]34 + $RelativePath + "sdelete.exe" + [char]34  
                     } else {  
                          $sDelete = [char]34 + $RelativePath + "sdelete64.exe" + [char]34  
                     }  
                     $Switches = "-accepteula -p" + [char]32 + $SecureDeletePasses + [char]32 + "-q" + [char]32 + [char]34 + $File.FullName + [char]34  
                     $ErrCode = (Start-Process -FilePath $sDelete -ArgumentList $Switches -Wait -PassThru).ExitCode  
                     If (($ErrCode -eq 0) -and ((Test-Path $File.FullName) -eq $false)) {  
                          $Output += "Success"  
                     } else {  
                          $Output += "Failed"  
                     }  
                } else {  
                     Remove-Item -Path $File.FullName -Force | Out-Null  
                     If ((Test-Path $File.FullName) -eq $false) {  
                          $Output += "Success"  
                     } else {  
                          $Output += "Failed"  
                     }  
                }  
                Write-Output $Output  
           }  
      } else {  
           $Output = "No Chat History Present"  
           Write-Output $Output  
      }  
 }  
   
 function Remove-MyJabberFilesFolder {  
 <#  
      .SYNOPSIS  
           Delete MyJabberFiles Folder  
        
      .DESCRIPTION  
           Delete the MyJabberFiles folder stores under %USERNAME%\documents and verifies it was deleted.  
        
      .EXAMPLE  
           PS C:\> Remove-MyJabberFilesFolder  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $MyJabberFilesFolder = Get-Item $env:USERPROFILE'\Documents\MyJabberFiles' -ErrorAction SilentlyContinue  
      If ($MyJabberFilesFolder -ne $null) {  
           $Output = "Deleting " + $MyJabberFilesFolder.Name + "....."  
           Remove-Item -Path $MyJabberFilesFolder -Recurse -Force | Out-Null  
           If ((Test-Path $MyJabberFilesFolder.FullName) -eq $false) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
           }  
           Write-Output $Output  
      } else {  
           $Output = "No MyJabberFiles folder present"  
           Write-Output $Output  
      }  
 }  
   
 Clear-Host  
 #Kill Cisco Jabber Process  
 $JabberClosed = Close-Process -ProcessName CiscoJabber  
 #Delete .DB files from %USERNAME%\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History  
 Remove-ChatFiles  
 #Delete %USERNAME%\documents\MyJabberFiles directory  
 Remove-MyJabberFilesFolder  
 #Reopen Jabber if it was open  
 If ($JabberClosed -eq $true) {  
      Open-Application -ApplicationName "Cisco Jabber" -Executable CiscoJabber.exe  
 }  
   

17 February 2017

Event 51 Drive Failure Reporting Tool

Posted By: Mick Pletcher - 1:28 PM










Last year, we had a high level executive that started having slowness and extended drive usage. When the help desk evaluated his system, they found it had been writing an event 51 to the event viewer logs. They were able to backup all of his data and build a new system for him before the drive completely failed. You can read more about event 51 here. While writing this script, I used SAPIEN's PowerShell Studio 2017 and it made writing the script a breeze, while also helping to streamline the code and documentation. I cannot say enough good things about this product!

I decided to write a reporting tool for this event so that IT professionals will be aware of this error before a complete failure occurs and there is data loss along with losses in production time.

While writing this script, I decided to make it applicable to admins who may not have SCCM. There are three parameters to call from command line: -SCCM if you want it to report to SCCM, -NetworkShare if you don't have SCCM and want it to report to a network share, and -NetworkSharePath which defines to network share to write to.

If you select -SCCM, the script creates a WMI class named DriveReporting and writes a count of error 51 logs to this WMI class instance. Each time the script is executed, it will delete the WMI class and create a new one so no old information may be left over. In order to get this to report to SCCM, you will need to import the WMI class into the hardware inventory. I have included a parameter called -SCCMImport that will create the WMI class and create an instance of five errors. This can then be imported into the hardware inventory of SCCM. The next time the script is executed, this WMI class will be deleted if no errors are detected. I suggest setting up the script as a package in SCCM to run daily during business hours, as it will likely get the most machines that are online if the environment has a lot of laptops.

For those admins with no SCCM server, you can select -NetworkShare while also defining -NetworkSharePath to write to a log file named <Computer Name>.log with the count of errors inside the log file. If no errors are detected and a log file exists, the script deletes it.

I made this video as a tutorial on using this script:



This is a screenshot I took with all parameters selected, except for the -SCCMImport, which is documented in the video.



You can download the script from here.


 <#  
      .SYNOPSIS  
           SMART Reporting  
        
      .DESCRIPTION  
           This script will query the event viewer logs for event ID 51. Event 51 is generated when a drive is in the beginning stages of failing. This script will is to be deployed to machines to generate a WMI entry if event 51 is read. If no event 51 exists, no WMI entry is generated to be read by SCCM.  
        
      .PARAMETER SCCM  
           Select this switch to write the results to WMI for reporting to SCCM.  
        
      .PARAMETER NetworkShare  
           Select this switch to write the results to a text file located on the specified network share inside a file named after the machine this script was executed on.  
        
      .PARAMETER NetworkSharePath  
           UNC path to write output reporting to  
        
      .PARAMETER SCCMImport  
           This is used to create a fake WMI entry so that it can be imported into SCCM.  
        
      .EXAMPLE  
           Setting up the initial import of the WMI Class to SCCM  
                powershell.exe -file SMARTReporting.ps1 -SCCMImport  
   
           Reporting to SCCM  
                powershell.exe -file SMARTReporting.ps1 -SCCM  
   
           Reporting to a Network Share  
                powershell.exe -file SMARTReporting.ps1 -NetworkShare -NetworkSharePath "\\server\path\Reporting"  
   
      .NOTES  
           ===========================================================================  
           Created with:   SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.127  
           Created on:     8/12/2016 11:02 AM  
           Created by:     Mick Pletcher  
           Organization:  
           Filename:       SMARTReporting.ps1  
           ===========================================================================  
 #>  
 param  
 (  
      [switch]$SCCM,  
      [switch]$NetworkShare,  
      [string]$NetworkSharePath,  
      [switch]$SCCMImport  
 )  
 function Initialize-HardwareInventory {  
 <#  
      .SYNOPSIS  
           Perform Hardware Inventory  
        
      .DESCRIPTION  
           Perform a hardware inventory via the SCCM client to report the WMI entry.  
        
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $Output = "Initiate SCCM Hardware Inventory....."  
      $SMSCli = [wmiclass] "\\localhost\root\ccm:SMS_Client"  
      $ErrCode = ($SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000001}")).ReturnValue  
      If ($ErrCode -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function New-WMIClass {  
 <#  
      .SYNOPSIS  
           Create New WMI Class  
        
      .DESCRIPTION  
           This will delete the specified WMI class if it already exists and create/recreate the class.  
        
      .PARAMETER Class  
           A description of the Class parameter.  
        
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If (($WMITest -ne "") -and ($WMITest -ne $null)) {  
           $Output = "Deleting " + $Class + " WMI class....."  
           Remove-WmiObject $Class  
           $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
           If ($WMITest -eq $null) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
                Exit 1  
           }  
           Write-Output $Output  
      }  
      $Output = "Creating " + $Class + " WMI class....."  
      $newClass = New-Object System.Management.ManagementClass("root\cimv2", [string]::Empty, $null);  
      $newClass["__CLASS"] = $Class;  
      $newClass.Qualifiers.Add("Static", $true)  
      $newClass.Properties.Add("Error51", [System.Management.CimType]::string, $false)  
      $newClass.Properties["Error51"].Qualifiers.Add("key", $true)  
      $newClass.Properties["Error51"].Qualifiers.Add("read", $true)  
      $newClass.Put() | Out-Null  
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If ($WMITest -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
           Exit 1  
      }  
      Write-Output $Output  
 }  
   
 function New-WMIInstance {  
 <#  
      .SYNOPSIS  
           Write new instance  
        
      .DESCRIPTION  
           Write a new instance reporting the last time the system was rebooted  
        
      .PARAMETER LastRebootTime  
           Date/time the system was last rebooted  
        
      .PARAMETER Class  
           WMI Class  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Error51,  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $Output = "Writing Error 51 information instance to" + [char]32 + $Class + [char]32 + "class....."  
      $Return = Set-WmiInstance -Class $Class -Arguments @{ Error51 = $Error51 }  
      If ($Return -like "*" + $Error51 + "*") {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function Remove-WMIClass {  
 <#  
      .SYNOPSIS  
           Delete WMIClass  
        
      .DESCRIPTION  
           Delete the WMI class from system  
        
      .PARAMETER Class  
           Name of WMI class to delete  
        
      .EXAMPLE  
                     PS C:\> Remove-WMIClass  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If (($WMITest -ne "") -and ($WMITest -ne $null)) {  
           $Output = "Deleting " + $Class + " WMI class....."  
           Remove-WmiObject $Class  
           $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
           If ($WMITest -eq $null) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
                Exit 1  
           }  
           Write-Output $Output  
      }  
 }  
   
 Clear-Host  
 #Retrieve number of times error 51 has been logged in the event viewer logs  
 [int]$Count = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 51 } -ErrorAction SilentlyContinue).Count  
 If ($SCCMImport.IsPresent) {  
      #Create WMI Class  
      New-WMIClass -Class DriveReporting  
      #Write a new WMI instance to the WMI class with a report of how many error 51 events were detected  
      New-WMIInstance -Class DriveReporting -Error51 5  
 } else {  
      If ($Count -gt 0) {  
           $Output = "Event 51 disk error has occurred $Count times."  
           Write-Output $Output  
           #Write error reporting to SCCM  
           If ($SCCM.IsPresent) {  
                #Delete the specified WMI class and recreate it for clean reporting  
                New-WMIClass -Class DriveReporting  
                #Write a new WMI instance to the WMI class with a report of how many error 51 events were detected  
                New-WMIInstance -Class DriveReporting -Error51 $Count  
                #Trigger an SCCM hardware inventory to report the errors to SCCM  
                Initialize-HardwareInventory  
           }  
           #Write error reporting to a network share  
           If ($NetworkShare.IsPresent) {  
                #Add a backslash to the end of the defined network share path if it does not exist  
                If ($NetworkSharePath[$NetworkSharePath.Length - 1] -ne "\") {  
                     $NetworkSharePath += "\"  
                }  
                #Define the log file to write the output to  
                $File = $NetworkSharePath + $env:COMPUTERNAME + ".log"  
                #Delete the log file if it already exists so a clean one will be written to  
                If ((Test-Path $File) -eq $true) {  
                     $Output = "Deleting " + $env:COMPUTERNAME + ".log....."  
                     Remove-Item -Path $File -Force | Out-Null  
                     If ((Test-Path $File) -eq $false) {  
                          $Output += "Success"  
                     } else {  
                          $Output += "Failed"  
                     }  
                     Write-Output $Output  
                }  
                #Create a new log file and write number of event 51 logs to it  
                $Output = "Creating " + $env:COMPUTERNAME + ".log....."  
                New-Item -Path $File -ItemType File -Force | Out-Null  
                Add-Content -Path $File -Value "Event 51 Count: $Count" -Force  
                If ((Test-Path $File) -eq $true) {  
                     $Output += "Success"  
                } else {  
                     $Output += "Failed"  
                }  
                Write-Output $Output  
           }  
      } else {  
           $Output = "No event 51 disk errors detected."  
           Write-Output $Output  
           #Delete the WMI class if it exists on the system since no errors were detected  
           If ($SCCM.IsPresent) {  
                Remove-WMIClass -Class DriveReporting  
           }  
           #Delete log file if it exists since no errors were detected  
           If ($NetworkShare.IsPresent) {  
                If ($NetworkSharePath[$NetworkSharePath.Length - 1] -ne "\") {  
                     $NetworkSharePath += "\"  
                }  
                $File = $NetworkSharePath + $env:COMPUTERNAME + ".log"  
                If ((Test-Path $File) -eq $true) {  
                     $Output = "Deleting " + $env:COMPUTERNAME + ".log....."  
                     Remove-Item -Path $File -Force | Out-Null  
                     If ((Test-Path $File) -eq $false) {  
                          $Output += "Success"  
                     } else {  
                          $Output += "Failed"  
                     }  
                     Write-Output $Output  
                }  
           }  
      }  
 }  
   

14 February 2017

Report Last Reboot Time to SCCM

Posted By: Mick Pletcher - 2:47 PM















We have started switching users over from desktops to laptops. In doing so, we realized that a good number of the laptops have not been rebooted in quite a while. The problem comes from sleep and hibernation mode. The LastBootUpTime property of Win32_OperatingSystem is not an accurate date/time. It considers a bootup if a system comes out of a sleep state, cold boot, or reboot. We were wanting to be able to know when a system is rebooted.

The event viewer logs can tell this by searching for the ID 6006. The 6006 event is generated when a system is shutdown or restarted, which is what I was looking for. You can read more on this event here.  To go one step further in the event the same ID is ever used in the future for other reporting, I included searching for "service was stopped". The query for the event is as follows: 

[string]$LastReboot = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 6006 } -MaxEvents 1 | Where-Object { $_.Message -like "*service was stopped*" }).TimeCreated 

I also reached out to the IT community and polled other admins on how they have tracked reboots. They gave me other events they use which include: 6005 (Last time the log service started), 6009 (MultiprocessorFree log is generated when a system boots up), and 27 (Windows 10 only returns a 0x0 when a system is booting up from a shutdown or restart). I have included these options in the script as parameters to be used at the admin's preference.

To make sure this reporting does not continue adding instances to the WMI class it creates, I included the part to delete and recreate the WMI class each time the script executes. The script will also initiate a hardware inventory to report the data up to SCCM. You will need to import the WMI class into SCCM in order for it to read the reboot information.

NOTE: If the Windows 10 fast startup option is enabled, these logs will not register. (Thanks to Ari Saastamoinen for this info.)

You can download the script from here

 <#  
      .SYNOPSIS  
           Report Last Reboot/Shutdown Time  
        
      .DESCRIPTION  
           This script will query the system logs for the last time the system was shutdown or rebooted. I have included four different logs that can be used for determining the last shutdown. I compiled this list from asking poling admins online on what methods they used to determine the last reboot/shutdown of a system. These methods were the most common responses. It will create a WMI class to record the date/time of the last reboot time. The script will then initiate an SCCM hardware inventory to push the data up to SCCM.  
        
      .PARAMETER EventLogServiceStopped  
           Specifies the use of event ID 6006 which is when the event log service was stopped, thereby signifying a system shutdown.  
        
      .PARAMETER KernelBootType  
           Specifies using the event ID 27 and looking for 'The boot type was 0x0' which is a full shutdown. This is a Windows 10 only feature.  
        
      .PARAMETER MultiprocessorFree  
           Specifies using event ID 6009 that is logged when a system starts up.  
        
      .PARAMETER EventLogServiceStarted  
           Specifies the use of event ID 6005 which is when the event log service was started, thereby signifying a system startup.  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135  
           Created on:       1/30/2017 1:45 PM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:         LastRebootTime.ps1  
           ===========================================================================  
 #>  
 param  
 (  
      [switch]$EventLogServiceStopped,  
      [switch]$KernelBootType,  
      [switch]$MultiprocessorFree,  
      [switch]$EventLogServiceStarted  
 )  
 function Initialize-HardwareInventory {  
 <#  
      .SYNOPSIS  
           Perform Hardware Inventory  
        
      .DESCRIPTION  
           Perform a hardware inventory via the SCCM client to report the WMI entry.  
        
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $Output = "Initiate SCCM Hardware Inventory....."  
      $SMSCli = [wmiclass] "\\localhost\root\ccm:SMS_Client"  
      $ErrCode = ($SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000001}")).ReturnValue  
      If ($ErrCode -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 function New-WMIClass {  
 <#  
      .SYNOPSIS  
           Create New WMI Class  
        
      .DESCRIPTION  
           This will delete the specified WMI class if it already exists and create/recreate the class.  
        
      .PARAMETER Class  
           A description of the Class parameter.  
        
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If (($WMITest -ne "") -and ($WMITest -ne $null)) {  
           $Output = "Deleting " + $Class + " WMI class....."  
           Remove-WmiObject $Class  
           $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
           If ($WMITest -eq $null) {  
                $Output += "Success"  
           } else {  
                $Output += "Failed"  
                Exit 1  
           }  
           Write-Output $Output  
      }  
      $Output = "Creating " + $Class + " WMI class....."  
      $newClass = New-Object System.Management.ManagementClass("root\cimv2", [string]::Empty, $null);  
      $newClass["__CLASS"] = $Class;  
      $newClass.Qualifiers.Add("Static", $true)  
      $newClass.Properties.Add("LastRebootTime", [System.Management.CimType]::string, $false)  
      $newClass.Properties["LastRebootTime"].Qualifiers.Add("key", $true)  
      $newClass.Properties["LastRebootTime"].Qualifiers.Add("read", $true)  
      $newClass.Put() | Out-Null  
      $WMITest = Get-WmiObject $Class -ErrorAction SilentlyContinue  
      If ($WMITest -eq $null) {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
           Exit 1  
      }  
      Write-Output $Output  
 }  
   
 function New-WMIInstance {  
 <#  
      .SYNOPSIS  
           Write new instance  
        
      .DESCRIPTION  
           Write a new instance reporting the last time the system was rebooted  
        
      .PARAMETER LastRebootTime  
           Date/time the system was last rebooted  
        
      .PARAMETER Class  
           WMI Class  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$LastRebootTime,  
           [ValidateNotNullOrEmpty()][string]$Class  
      )  
        
      $Output = "Writing Last Reboot information instance to" + [char]32 + $Class + [char]32 + "class....."  
      $Return = Set-WmiInstance -Class $Class -Arguments @{ LastRebootTime = $LastRebootTime }  
      If ($Return -like "*" + $LastRebootTime + "*") {  
           $Output += "Success"  
      } else {  
           $Output += "Failed"  
      }  
      Write-Output $Output  
 }  
   
 Clear-Host  
 #Get the log entry of the last time the Event Log service was stopped to determine a reboot  
 If ($KernelBootType.IsPresent) {  
      [string]$LastReboot = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 27 } -MaxEvents 1 | Where-Object { $_.Message -like "*boot type was 0x0*" }).TimeCreated  
 }  
 If ($EventLogServiceStarted.IsPresent) {  
      [string]$LastReboot = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 6005 } -MaxEvents 1 | Where-Object { $_.Message -like "*service was started*" }).TimeCreated  
 }  
 If ($EventLogServiceStopped.IsPresent) {  
      [string]$LastReboot = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 6006 } -MaxEvents 1 | Where-Object { $_.Message -like "*service was stopped*" }).TimeCreated  
 }  
 If ($MultiprocessorFree.IsPresent) {  
      [string]$LastReboot = (Get-WinEvent -FilterHashtable @{ logname = 'system'; ID = 6009 } -MaxEvents 1 | Where-Object { $_.Message -like "*Multiprocessor Free*" }).TimeCreated  
 }  
   
 $Output = "Last reboot/shutdown: " + $LastReboot  
 Write-Output $Output  
 #Delete old WMI Class and create new one  
 New-WMIClass -Class "RebootInfo"  
 #Add last reboot date/time as WMI instance  
 New-WMIInstance -LastRebootTime $LastReboot -Class "RebootInfo"  
 #Initialize SCCM hardware inventory to report information back to SCCM  
 Initialize-HardwareInventory  
   

Copyright © 2013 Mick's IT Blogs™ is a registered trademark.