28 February 2017

Bitlocker Recovery Password Utility

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

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

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 taking 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 set up 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 shut down Jabber 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.

UPDATE 1:

I came back and updated this script so that it will now parse through all user profiles and securely delete the appropriate files. Another change made is with the sdelete.exe file. A GPO is now used to do the following:

  • Push the sdelete.exe or sdelete64.exe file to all systems in the %WINDIR%\System32 directory. I use a GPO to push this file to the %Windir%\System32 directory so that it is available everywhere on the system in the event I want to do a secure delete on anything else.
  • Push the .PS1 script to the designated directory on the computer so it can be executed locally without network connectivity. I also use the same GPO to push this file down. 
  • Create a scheduled task to execute the .PS1 file on the system at the designated interval. This is also created by a GPO.
You can download the script from my GitHub site located here.

UPDATE 2:

I updated this script to function as a one-liner in case you want to run this as the end-user at logon, logoff, etc, which is what I have ended up doing. I also split this off into two one-liners. One is for a secured delete using sdelete64.exe and the other uses Remove-Item.

Secured Delete One-Liner:
 powershell.exe -command "&{$Deletes='3';Get-Process -Name CiscoJabber -ErrorAction SilentlyContinue | Stop-Process;Do {$Process = Get-Process -Name CiscoJabber -ErrorAction SilentlyContinue} While ($Process -ne $null);Get-childItem -Path $Env:LOCALAPPDATA'\Cisco\Unified Communications\Jabber\CSF\History' -Filter *.db | ForEach-Object {$arguments='-accepteula'+[char]32+'-p'+[char]32+$Deletes+[char]32+[char]34+$_.FullName+[char]34;Start-Process -FilePath $env:windir'\System32\sdelete64.exe' -ArgumentList $Arguments -WindowStyle Hidden};Get-Item -Path $env:USERPROFILE'\Documents\MyJabberFiles' -ErrorAction SilentlyContinue | Where-Object {$arguments='-accepteula'+[char]32+'-p'+[char]32+$Deletes+[char]32+[char]34+$_.FullName+[char]34;Start-Process -FilePath $env:windir'\System32\sdelete64.exe' -ArgumentList $Arguments -WindowStyle Hidden};Start-Process -FilePath (Get-ChildItem -Path $env:ProgramFiles,${env:ProgramFiles(x86)} -Filter CiscoJabber.exe -Recurse -ErrorAction SilentlyContinue).FullName}"  

Unsecured Delete One-Liner
 powershell.exe -command "&{Get-Process -Name CiscoJabber -ErrorAction SilentlyContinue | Stop-Process;Do {$Process = Get-Process -Name CiscoJabber -ErrorAction SilentlyContinue} While ($Process -ne $null);Get-childItem -Path $Env:LOCALAPPDATA'\Cisco\Unified Communications\Jabber\CSF\History' -Filter *.db | ForEach-Object { Remove-Item -Path $_.FullName -Force };Get-Item -Path $env:USERPROFILE'\Documents\MyJabberFiles' -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force;Start-Process -FilePath (Get-ChildItem -Path $env:ProgramFiles,${env:ProgramFiles(x86)} -Filter CiscoJabber.exe -Recurse -ErrorAction SilentlyContinue).FullName}"  


Main Script:
 <#  
      .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  
           Updated on:     12/27/2018 3:34 PM  
           Created by:       Mick Pletcher  
           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 ()  
        
      $Users = Get-ChildItem -Path $env:HOMEDRIVE"\users" -Exclude 'Administrator', 'public', 'iCreateService', 'sccmadmin', 'Default'  
      foreach ($User in $Users) {  
           #Get Jabber Chat history files  
           $History = $User.FullName + '\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History'  
           $ChatHistoryFiles = Get-ChildItem -Path $History -Filter *.db  
           If ($ChatHistoryFiles -ne $null) {  
                foreach ($File in $ChatHistoryFiles) {  
                     $Output = "Deleting " + $File.Name + "....."  
                     If ($SecureDelete.IsPresent) {  
                          $RelativePath = Get-RelativePath  
                          $sDelete = [char]34 + $env:windir + "\system32\" + "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 ()  
        
      $Users = Get-ChildItem -Path $env:HOMEDRIVE"\users" -Exclude 'Administrator', 'public', 'iCreateService', 'sccmadmin', 'Default'  
      foreach ($User in $Users) {  
           $Folder = $User.FullName + '\Documents\MyJabberFiles'  
           $MyJabberFilesFolder = Get-Item $Folder -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 each %USERNAME%\AppData\Local\Cisco\Unified Communications\Jabber\CSF\History  
 Remove-ChatFiles  
 #Delete each %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

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

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  
   

07 February 2017

ImageX Error while Creating MDT Task Sequence

While creating an MDT task sequence in SCCM, I encountered the error message: System.IO.FileNotFoundException: Could not find file '\imagex.exe'.


I started Googling the error and the best info I found was to either copy over the imageX.exe or update the distribution point. Neither fix worked. After troubleshooting the issue for a couple of hours, I thought that maybe there was an extension issue between MDT and SCCM, so I removed the extension using the Configure ConfigMgr Integration tool. I then readded the extension using the same tool. This fixed the error message and it now creates an MDT task sequence with no problems.

06 February 2017

Automated Dell Command Update

While working on implementing the new Windows 10 build, I decided to update the Dell Command | Update process. The old script was still looking at the old DCSU and had many inefficiencies that needed to be updated. I also wanted to add new features to the script for logging purposes. With using SAPIEN's PowerShell Studio, the process to update this script was a breeze.

The new script is written so that it can be executed from a command line, build, or a deployment. This now includes the option to write a log file to a specified location by %model%\%ComputerName%. It will delete the old computer name directory and create a new if it already exists. The logs give you the ability to keep track of drivers that may not be applying correctly and you need to inject into SCCM.

Below is how I configured the script in SCCM. The portions I blackened out are the location of the script. It will likely need to be executed as a domain admin account so that it has access to the internet, otherwise you could use the Run PowerShell Script Type.



You can download the script from here.


 <#  
      .SYNOPSIS  
           Update Dell Drivers  
        
      .DESCRIPTION  
           Update Dell drivers using the Dell Command Update.  
        
      .PARAMETER Logging  
           Specifies if logging is to take place  
        
      .PARAMETER LogLocation  
           Location where to write the driver logs  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135  
           Created on:       2/3/2017 2:21 PM  
           Created by:       Mick Pletcher  
           Organization:  
           Filename:         DellDriverUpdate.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [switch]$Logging,  
      [string]$LogLocation  
 )  
 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  
      Return $OSArchitecture  
      #Returns 32-bit or 64-bit  
 }  
   
 function Get-DellCommandUpdateLocation {  
 <#  
      .SYNOPSIS  
           Find dcu-cli.exe  
        
      .DESCRIPTION  
           Locate dcu-cli.exe as it may reside in %PROGRAMFILES% or %PROGRAMFILES(X86)%  
        
 #>  
        
      [CmdletBinding()][OutputType([string])]  
      param ()  
        
      $Architecture = Get-Architecture  
      If ($Architecture -eq "32-bit") {  
           $File = Get-ChildItem -Path $env:ProgramFiles -Filter "dcu-cli.exe" -ErrorAction SilentlyContinue -Recurse  
      } else {  
           $File = Get-ChildItem -Path ${env:ProgramFiles(x86)} -Filter "dcu-cli.exe" -ErrorAction SilentlyContinue -Recurse  
      }  
      Return $File.FullName  
 }  
   
 function Invoke-DriverUpdate {  
 <#  
      .SYNOPSIS  
           Execute Dell Command Update  
        
      .DESCRIPTION  
           This will initiate the Dell Command Update using the dcu-cli.exe  
        
      .PARAMETER Executable  
           dcu-cli.exe  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()]$Executable  
      )  
        
      If ($Logging.IsPresent) {  
           $Model = (Get-WmiObject -Class Win32_ComputerSystem).Model  
           If ($LogLocation[$LogLocation.Length - 1] -ne "\") {  
                $Location = $LogLocation + "\" + $Model  
           } else {  
                $Location = $LogLocation + $Model  
           }  
           If ((Test-Path $LogLocation) -eq $false) {  
                New-Item -Path $LogLocation -ItemType Directory -Force | Out-Null  
           }  
           If ((Test-Path $Location) -eq $false) {  
                New-Item -Path $Location -ItemType Directory -Force | Out-Null  
           }  
           $Location += "\" + $env:COMPUTERNAME  
           If ((Test-Path $Location) -eq $true) {  
                Remove-Item -Path $Location -Recurse -Force  
           }  
           $Arguments = "/log" + [char]32 + [char]34 + $Location + [char]34  
      } else {  
           $Arguments = [char]32  
      }  
      Start-Process -FilePath $Executable -ArgumentList $Arguments -Wait -Passthru | Out-Null  
 }  
   
   
 Clear-Host  
 #Find dcu-cli.exe  
 $EXE = Get-DellCommandUpdateLocation  
 #Install Dell drivers  
 Invoke-DriverUpdate -Executable $EXE  
   

01 February 2017

Using Registry Keys to configure MSI Installations

After posting the video on how to use registry keys to pre-configure the settings of an MSI during installation, I got a lot of interest, so I decided to create this blog to explain how it works and why it can be beneficial. This method should not be considered as a standard use. It has a very small window of uses in deployments.

Some apps that I deploy are updated on a continuous basis and use MSI installers. The companies never change the MSI properties. Because of never changing the properties in the MSI database tables, this gives the opportunity to create a PowerShell installer script that pushes the registry keys down to the system before it installs the application. Those registry keys control the way the MSI functions during installation the same way calling properties at the msiexec.exe command line does. If you have apps that rarely change the properties of the MSI, this way can make future upgrades a lot easier.

Here is the video I posted on YouTube: