Mick's IT Blogs

Mick's IT Blogs

27 April 2017

Automated Import of PowerShell SCCM Module

Posted By: Mick Pletcher - 3:25 PM















While writing quite a few PowerShell scripts for SCCM, I got tired of having to look up the location of the SCCM PowerShell module to import. I decided while writing the current PowerShell SCCM script, I would automate this process from now on. This makes it a snap using SAPIEN's PowerShell Studio to make this function a snippet and quickly add it each time I write a new SCCM script.

This script allows you to import the SCCM module without having to look up the location. The only parameter you have to specify is the -SCCMServer, which is the name of the SCCM server. The script will then connect to the SCCM server, get the parent installation directory, including the drive letter, and then search for the ConfigurationManager.psd1 file. If it finds more than one file, it will import the latest one.

You can use the function in this script in other scripts to make the process a breeze.

The script can be downloaded from my GitHub repository.


 <#  
      .SYNOPSIS  
           Imports the SCCM PowerShell Module  
        
      .DESCRIPTION  
           This function will import the SCCM PowerShell module without the need of knowing the location. The only thing that needs to be specified is the name of the SCCM server.   
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.139  
           Created on:       4/26/2017 3:56 PM  
           Created by:       Mick Pletcher  
           Filename:         ImportSCCMModule.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param ()  
   
 function Import-SCCMModule {  
 <#  
      .SYNOPSIS  
           Import SCCM Module  
        
      .DESCRIPTION  
           Locate the ConfigurationManager.psd1 file and import it.  
        
      .PARAMETER SCCMServer  
           Name of the SCCM server to connect to.  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$SCCMServer  
      )  
        
      #Get the architecture of the specified SCCM server  
      $Architecture = (get-wmiobject win32_operatingsystem -computername $SCCMServer).OSArchitecture  
      #Get list of installed applications  
      $Uninstall = Invoke-Command -ComputerName $SCCMServer -ScriptBlock { Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" -Force -ErrorAction SilentlyContinue }  
      If ($Architecture -eq "64-bit") {  
           $Uninstall += Invoke-Command -ComputerName $SCCMServer -ScriptBlock { Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" -Force -ErrorAction SilentlyContinue }  
      }  
      #Get the registry key that specifies the location of the SCCM installation drive and directory  
      $RegKey = ($Uninstall | Where-Object { $_ -like "*SMS Primary Site*" }) -replace 'HKEY_LOCAL_MACHINE', 'HKLM:'  
      $Reg = Invoke-Command -ComputerName $SCCMServer -ScriptBlock { Get-ItemProperty -Path $args[0] } -ArgumentList $RegKey  
      #Parse the directory listing  
      $Directory = (($Reg.UninstallString).Split("\", 4) | Select-Object -Index 0, 1, 2) -join "\"  
      #Locate the location of the SCCM module  
      $Module = Invoke-Command -ComputerName $SCCMServer -ScriptBlock { Get-ChildItem -Path $args[0] -Filter "ConfigurationManager.psd1" -Recurse } -ArgumentList $Directory  
      #If more than one module is present, use the latest one  
      If ($Module.Length -gt 1) {  
           foreach ($Item in $Module) {  
                If (($NewModule -eq $null) -or ($Item.CreationTime -gt $NewModule.CreationTime)) {  
                     $NewModule = $Item  
                }  
           }  
           $Module = $NewModule  
      }  
      #format the $Module unc path  
      [string]$Module = "\\" + $SCCMServer + "\" + ($Module.Fullname -replace ":", "$")  
      #Import the SCCM module  
      Import-Module -Name $Module  
 }  
   
 Import-SCCMModule -SCCMServer "SCCMServer"  
   

14 April 2017

Application Build Reporting for MDT and SCCM

Posted By: Mick Pletcher - 11:31 AM















A few years ago, I had published a PowerShell module that contained a function to log all app installs during a build process. With the project of upgrading systems to Windows 10, I decided to explore that once again.

This new script I have written is designed to query the programs and features registry entries to verify if an application is installed and to write that verification to a .CSV file. The purpose of this is to generate a report that is easy to open and see if all applications were successfully installed.

When I first started designing this script, I intended to have it read the ts.xml file from MDT and query the task sequence via PowerShell in SCCM. It was going to grab the name of the application that was exactly how it was listed in programs and features. That method had issues for the fact that some applications install more than one app during the installation. If you wanted to verify that more than one app was installed, then the script would not work correctly.

After much thought, I decided that writing a script in which I could designate in the parameters what application to search for would be much better. The script now becomes a task sequence after the installation sequence of the app. This allows a separate task for each app that an installation might install to be done.

Here is how I used the script in my task sequence. I build my reference images in MDT and deploy through SCCM. As you can see below, I have a task sequence to install that app and the next sequence is to check if it is installed and write to the CSV file.

Each of the task sequence checks are setup as Run PowerShell Scripts. In MDT, you will need to copy the PowerShell script to the %MDTDeploymentShare%\Scripts folder.
In the parameters field, you will need the following info:

  • -Application
  • -LogFileName
  • -LogFileLocation
  • -ExactFileName
The Application parameter will be the one that you will definitely need to define in the MDT task sequence because it will be different for each app. This parameter can be named either a partial name or the exact name as displayed in the Programs and Features. Such applications as Java Runtime can use a partial name 'Java 8' to get any version of the Java 8 that may be installed. Java 8 is always displayed Java 8u60 for instance.

The LogFileName parameter is what the logfile will be called. I define it in the task sequence because %OSDCOMPUTERNAME% is the computer name defined in the user input fields of an MDT image. If you hardcoded $env:computername to the parameter in the script, the computername you input will not be the same. 

The LogFileLocation parameter defines where you want the CSV file to be written.

The ExactFileName parameter specifies to search the programs and features for the name that matches exactly what is defined in the Application parameter. I ran into an instance with Microsoft Office 2016 where it had more than one entry. It still had two entries even using the exact name. In this case, the script measures the length of the registry entry and chooses the larger. I found if there are two entries with the exact names, the larger one is what is displayed in Programs and Features. 

Here is an example of Dell Command | Configure:


-Application 'Dell Command | Configure' -LogFileName %OSDCOMPUTERNAME% -LogFileLocation '\\Directory\ApplicationBuildReport\Reports'

This is what the CSV file report looks like after a reference build is completed. Some of the registry entries include the version within the filename.

As you can see, it makes for an easy way to check if everything got installed correctly in a build. One more thing I do in my reference image task sequence is to suspend the imaging process so I can check this report before a reference image is generated. That way, if items are missing, I can either install them manually and then proceed with grabbing an image or fix the problem and then restart the image all over.

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


 <#  
      .SYNOPSIS  
           Check Application Install  
        
      .DESCRIPTION  
           This script will check if a specified application appears in the programs and features.  
        
      .PARAMETER Application  
           Name of application in the programs and features. It can be a partial name or the complete name.  
        
      .PARAMETER LogFileName  
           Name of the LogFileName containing the list of applications installed on the machine  
        
      .PARAMETER LogFileLocation  
           Location where to write the log file  
        
      .PARAMETER ExactFileName  
           Specifies to search for the exact filename, otherwise the script will search for filename that contain the designated search criteria.  
        
      .NOTES  
           ===========================================================================  
           Created with:    SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.138  
           Created on:      4/4/2017 4:51 PM  
           Created by:      Mick Pletcher  
           Filename:        AppChecker.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [ValidateNotNullOrEmpty()][string]$Application,  
      [ValidateNotNullOrEmpty()][string]$LogFileName,  
      [string]$LogFileLocation,  
      [switch]$ExactFileName  
 )  
   
 function New-LogFile {  
 <#  
      .SYNOPSIS  
           Create new build log  
        
      .DESCRIPTION  
           This function will compare the date/time of the first event viewer log with the date/time of the log file to determine if it needs to be deleted and a new one created.  
        
      .PARAMETER LogFile  
           Full name of log file including the unc address  
        
      .EXAMPLE  
           PS C:\> New-LogFile  
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param  
      (  
           [ValidateNotNullOrEmpty()][string]$Log  
      )  
        
      #Get the creation date/time of the first event viewer log  
      $LogFile = Get-ChildItem -Path $LogFileLocation -Filter $LogFileName -ErrorAction SilentlyContinue  
      Write-Output "Log File Name: $LogFile"  
      $Output = "LogFile Creation Date: " + $LogFile.CreationTime  
      Write-Output $Output  
      If ($LogFile -ne $null) {  
           $OSInstallDate = Get-WmiObject Win32_OperatingSystem | ForEach-Object{ $_.ConvertToDateTime($_.InstallDate) -f "MM/dd/yyyy" }  
           Write-Output "    OS Build Date: $OSInstallDate"  
           If ($LogFile.CreationTime -lt $OSInstallDate) {  
                #Delete old log file  
                Remove-Item -Path $LogFile.FullName -Force | Out-Null  
                #Create new log file  
                New-Item -Path $Log -ItemType File -Force | Out-Null  
                #Add header row  
                Add-Content -Path $Log -Value "Application,Version,TimeStamp,Installation"  
           }  
      } else {  
           #Create new log file  
           New-Item -Path $Log -ItemType File -Force | Out-Null  
           #Add header row  
           Add-Content -Path $Log -Value "Application,Version,TimeStamp,Installation"  
      }  
 }  
   
 Clear-Host  
 #If the LogFileName is not predefined in the Parameter, then it is named after the computer name  
 If (($LogFileName -eq $null) -or ($LogFileName -eq "")) {  
      If ($LogFileName -notlike "*.csv*") {  
           $LogFileName += ".csv"  
      } else {  
           $LogFileName = "$env:COMPUTERNAME.csv"  
      }  
 } elseIf ($LogFileName -notlike "*.csv*") {  
           $LogFileName += ".csv"  
 }  
 #Add backslash to end of UNC path  
 If ($LogFileLocation[$LogFileLocation.Length - 1] -ne "\") {  
      $File = $LogFileLocation + "\" + $LogFileName  
 } else {  
      $File = $LogFileLocation + $LogFileName  
 }  
 #Create a new log file  
 New-LogFile -Log $File  
 #Get list of installed applications from programs and features  
 $Uninstall = Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" -Force -ErrorAction SilentlyContinue  
 $Uninstall += Get-ChildItem -Path REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" -Force -ErrorAction SilentlyContinue  
 #Check if the list of Applications contains the search query  
 If ($ExactFileName.IsPresent) {  
      $ApplicationInstall = $Uninstall | ForEach-Object { Get-ItemProperty $_.PsPath } | Where-Object { $_.DisplayName -eq $Application }  
 } else {  
      $ApplicationInstall = $Uninstall | ForEach-Object { Get-ItemProperty $_.PsPath } | Where-Object { $_.DisplayName -like "*" + $Application + "*" }  
 }  
 #If more than one registry entry, select larger entry that contains more information  
 If ($ApplicationInstall.length -gt 1) {  
      $Size = 0  
      for ($i = 0; $i -lt $ApplicationInstall.length; $i++) {  
           If (([string]$ApplicationInstall[$i]).length -gt $Size) {  
                $Size = ([string]$ApplicationInstall[$i]).length  
                $Temp = $ApplicationInstall[$i]  
           }  
      }  
      $ApplicationInstall = $Temp  
 }  
 #Exit with error code 0 if the app is installed, otherwise exit with error code 1  
 If ($ApplicationInstall -ne $null) {  
      $InstallDate = (($ApplicationInstall.InstallDate + "/" + $ApplicationInstall.InstallDate.substring(0, 4)).Substring(4)).Insert(2, "/")  
      $Output = $ApplicationInstall.DisplayName + "," + $ApplicationInstall.Version + "," + $InstallDate + "," + "Success"  
      Add-Content -Path $File -Value $Output  
      Write-Host "Exit Code: 0"  
      Exit 0  
 } else {  
      $Output = $Application + "," + "," + "," + "Failed"  
      Add-Content -Path $File -Value $Output  
      Write-Host "Exit Code: 1"  
      Exit 1  
 }  
   

29 March 2017

SCCM Active Directory Old and Corrupt System Reporting Tool

Posted By: Mick Pletcher - 11:04 AM















We wanted a comprehensive report of systems to be automatically generated on a monthly basis with the following information:


  • System Name
  • IP Address
  • Last Logon Time Stamp
  • Is it pingable?
  • Is the SCCM client installed
  • Is the SCCM client active
  • Last active time stamp of the SCCM client
I decided to write this script that combines DNS, SCCM, and AD information into one comprehensive report that can be filtered in Excel. 

The script requires three PowerShell modules to work:
  • ConfigurationManager.psd1
  • DNSClient.psd1
  • ActiveDirectory.psd1
On the system you will be executing this script from, RSAT will be required to execute it. 

The script will take a while to execute, depending on how many systems are in your environment. Here is a sample screenshot I took after running the report:


As you can see in the screenshot, the data can be very helpful in finding systems that may be gone, but were not deleted in AD and/or SCCM. It can also show you systems were the client may be busted. The report is generated and placed in the same location as the script. 

While writing this script, I used SAPIEN's PowerShell Studio and must say that it made writing this a breeze. It helps in documenting and making the code much more efficient.

You can download the script from my GitHub site

 <#  
      .SYNOPSIS  
           System Status Reporting Tool  
        
      .DESCRIPTION  
           This script will generate a report that pulls from the SCCM All Systems collection, active directory, and the DNS. The script will first get a list of All Systems that is typically populated by active directory. It will then iterate through the list getting the system name from SCCM, IP address from DNS, last logon time stamp from AD, if it is pingable from PowerShell, if the SCCM client is installed, if the client is active, and the last active time of the client. This information is put in a report form and written both to a CSV file and to the display. The report will show systems without the SCCM client, systems that have not been online for a long time, and systems that may have a corrupt client.  
        
      .PARAMETER SiteCode  
           SCCM site code needed to execute the configuration manager cmdlets.  
        
      .PARAMETER SCCMModule  
           Path to the configuration manager PowerShell module  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.136  
           Created on:       3/28/2017 9:54 AM  
           Created by:       Mick Pletcher  
           Filename:         SCCMADReport.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [ValidateNotNullOrEmpty()][string]$SiteCode,  
      [ValidateNotNullOrEmpty()][string]$SCCMModule  
 )  
 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  
 }  
   
 Clear-Host  
 Import-Module DnsClient  
 Import-Module ActiveDirectory  
 Import-Module -Name $SCCMModule  
 #Format sitecode  
 If ($SiteCode[$SiteCode.Length - 1] -ne ":") {  
      $SiteCode = $SiteCode + ":"  
 }  
 #Get location of current powershell connection  
 $Location = (get-location).Path.Split("\")[0]  
 #Change connection to configuration manager  
 Set-Location $SiteCode  
 #Get list of all systems in SCCM  
 $Systems = Get-CMDevice -CollectionName "All Systems" | Where-Object { $_.Name -notlike "*Unknown Computer*" }  
 #Create Reports array  
 $Report = @()  
 foreach ($System in $Systems) {  
      #Get SCCM info for $System  
      $SCCMSystemInfo = $Systems | Where-Object { $_.Name -eq $System.Name }  
      #Get the last logon timestamp from active directory  
      Try {  
           $LLTS = [datetime]::FromFileTime((get-adcomputer $System.Name -properties LastLogonTimeStamp -ErrorAction Stop).LastLogonTimeStamp).ToString('d MMMM yyyy')  
      } Catch {  
           $Output = $System.Name + " is not in active directory"  
           Write-Output $Output  
      }  
      #Test if the system is pingable  
      $Pingable = Test-Connection -ComputerName $System.Name -Count 2 -Quiet  
      #Get the ipaddress for the system  
      Try {  
           $IPAddress = (Resolve-DnsName -Name $System.Name -ErrorAction Stop).IPAddress  
      } Catch {  
           $Output = $System.Name + " IP address cannot be resolved"  
           Write-Output $Output  
      }  
      $Object = New-Object -TypeName System.Management.Automation.PSObject  
      $Object | Add-Member -MemberType NoteProperty -Name Name -Value $System.Name  
      $Object | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress  
      $Object | Add-Member -MemberType NoteProperty -Name ADLastLogon -Value $LLTS  
      $Object | Add-Member -MemberType NoteProperty -Name Pingable -Value $Pingable  
      $Object | Add-Member -MemberType NoteProperty -Name SCCMClient -Value $SCCMSystemInfo.IsClient  
      $Object | Add-Member -MemberType NoteProperty -Name SCCMActive -Value $SCCMSystemInfo.IsActive  
      $Object | Add-Member -MemberType NoteProperty -Name SCCMLastActiveTime -Value $SCCMSystemInfo.LastActiveTime  
      $Report += $Object  
      #Clear variables if they exist so previous data is not used for systems that have null values  
      If ($IPAddress) {  
           Remove-Variable -Name IPAddress -Force  
      }  
      If ($LLTS) {  
           Remove-Variable -Name LLTS -Force  
      }  
      If ($Pingable) {  
           Remove-Variable -Name Pingable -Force  
      }  
      If ($SCCMInfo) {  
           Remove-Variable -Name SCCMInfo -Force  
      }  
 }  
 #Change connection to local system  
 Set-Location $Location  
 Clear-Host  
 #Sort report by computer name  
 $Report = $Report | Sort-Object -Property Name  
 #Get the path this script is being executed from  
 $RelativePath = Get-RelativePath  
 #Path and filename to write the report to  
 $File = $RelativePath + "SCCMReport.csv"  
 #Delete old report file  
 If ((Test-Path $File) -eq $true) {  
      Remove-Item -Path $File -Force  
 }  
 #Write report to CSV file  
 $Report | Export-Csv -Path $File -Encoding UTF8 -Force  
 #Write Report to screen  
 $Report | Format-Table  

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  
 }  
   

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