11 September 2019

Zero Touch Dell Command Update for SCCM and MDT

I have used the Dell Command | Update in the build for quite some time for managing the drivers on systems because it makes it a hand-off approach with little setup and reliable updates direct from Dell. The one thing I have wanted to be able to rerun this task several times without having to have duplicate tasks in the task sequence. Sometimes there are multiple reboots required because not all drivers can be installed at the same time.

I finally discovered how ZTIWindowsUpdate.wsf reboots and reruns itself without corrupting the task sequence and I have applied the same code to this script. 

This script will run the dcu-cli.exe to both install updates and generate inventory.xml and activitylog.xml files. The script then reads the activitylog.xml file to see if any drivers were installed. If not, the script ends. If there were updates installed, the script creates a rebootcount.log file if it does not exist, that contains the number of reboots that have been performed. It will increment that number inside the file each time the system is rebooted and the script is rerun. This had to be included because a few updates Dell deploys do not register with the Dell Command | Update and reinstall every time it is run. Because of that, I limited the script to run 5 times like the ZTIWindowsUdpates.wsf does. I wrote in another blog entry why a task sequence variable cannot be used here to store the reboot count. 

Once the script either has no more updates to install or has run 5 times, it will remove both xml files and end so that SCCM/MDT can continue to the next task. 

The script can be downloaded from my GitHub site


 <#  
      .SYNOPSIS  
           Dell Driver Update  
        
      .DESCRIPTION  
           This script executes the Dell Command | Update and reboots MDT or SCCM up to five times when new updates are available. The reason for the 5 reboot limit is because some Dell updates have been know to not leave markers and will cause the Dell Command | Update to rerun indefinitely.  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.142  
           Created on:       7/18/2019 1:57 PM  
           Created by:       Mick Pletcher  
           Filename:         ZTIDellDriverUpdate.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param ()  
 #Delete old logs if they exist  
 Remove-Item -Path ($env:windir + '\temp\ActivityLog.xml') -ErrorAction SilentlyContinue -Force  
 Remove-Item -Path ($env:windir + '\temp\inventory.xml') -ErrorAction SilentlyContinue -Force  
 #Update the system with the latest drivers while also writing log files to the %windir%\temp directory  
 $ErrCode = (Start-Process -FilePath ((Get-ChildItem -Path $env:ProgramFiles, ${env:ProgramFiles(x86)} -Filter 'dcu-cli.exe' -Recurse).FullName) -ArgumentList ('/log ' + $env:windir + '\temp') -Wait).ExitCode  
 #Read the ActivityLog.xml file  
 $File = (Get-Content -Path ($env:windir + '\temp\ActivityLog.xml')).Trim()  
 #if no updates were found or updates were applied and no required reboot is necessary, then delete the log files  
 If (('<message>CLI: No application component updates found.</message>' -in $File) -and (('<message>CLI: No available updates can be installed.</message>' -in $File) -or ('<message>CLI: No updates are available.</message>' -in $File))) {  
      Remove-Item -Path ($env:windir + '\temp\ActivityLog.xml') -ErrorAction SilentlyContinue -Force  
      Remove-Item -Path ($env:windir + '\temp\inventory.xml') -ErrorAction SilentlyContinue -Force  
      Remove-Item -Path ($env:TEMP + '\RebootCount.log') -ErrorAction SilentlyContinue -Force  
 } else {  
      #Create the file containing number of times this script has rerun if it does not exist  
      If ((Test-Path ($env:TEMP + '\RebootCount.log')) -eq $false) {  
           New-Item -Path ($env:TEMP + '\RebootCount.log') -ItemType File -Value 0 -Force  
      }  
      #Reboot the machine and rerun the Dell Driver Updates  
      If (([int](Get-Content -Path ($env:TEMP + '\RebootCount.log'))) -lt 5) {  
           #Microsoft SCCM/MDT environmental variables  
           $TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment  
           #Reboot the machine once this task is completed and restart the task sequence  
           $TSEnv.Value('SMSTSRebootRequested') = $true  
           #Rerun the same task  
           $TSEnv.Value('SMSTSRetryRequested') = $true  
           #increment the reboot counter  
           New-Item -Path ($env:TEMP + '\RebootCount.log') -ItemType File -Value ([int](Get-Content -Path ($env:TEMP + '\RebootCount.log')) + 1) -Force  
      #End the update process if run 5 or more times, delete all associated log files, and proceed to the next task  
      } else {  
           Remove-Item -Path ($env:windir + '\temp\ActivityLog.xml') -ErrorAction SilentlyContinue -Force  
           Remove-Item -Path ($env:windir + '\temp\inventory.xml') -ErrorAction SilentlyContinue -Force  
           Remove-Item -Path ($env:TEMP + '\RebootCount.log') -ErrorAction SilentlyContinue -Force  
      }  
 }  
   

05 September 2019

Custom Task Sequence Variables and the SMSTSRebootRequested

While writing a new PowerShell script for SCCM, I needed to be able to keep track of how many times a system had rebooted when using the SMSTSRebootRequested. The apparent solution, at least what I initially thought, was to create a TS variable and increment it upon each reboot.

It ended up never ceasing the reboot process, and the task reran indefinitely. I began debugging the variables by using message boxes to display the value of the associated TS variable. I found the newly created TS variable was disappearing every time the system rebooted. I proceeded to comment out the SMSTSRebootRequested line and made a copy of the task so that it would not rerun itself, but would continue to run the very next task, which was the exact same thing. Sure enough, upon executing the second task, the values did increment and had not been cleared out.

The solution to this was to write the values assigned to the custom task sequence variable to a text file on the drive that would be changed each time the task sequence reran. At the last execution, the file is deleted. 

30 August 2019

SCCM/MDT Windows Updates Installer

One of the issues I have had when moving the build process from MDT to SCCM has been windows updates. Windows updates are not available in the SCCM build if it does not already deploy the updates to machines. Except for servers, the user machines are configured to install updates pushed down by Microsoft as shown below. Before asking about managing the updates, I do have tools put in place to be able to quickly stop updates from installing and remove updates if issues come up.


To get updates installed in the SCCM build process, I started by downloading and installing the PSWindowsUpdate PowerShell Module written by Michal Gajda. This module is fantastic for managing updates.

Next, I wrote the following PowerShell script that does the following things. The first thing that needs to be done is to make sure the PowerShellGet module is present before running the script. The script will check if the latest version of PSWindowsUpdate is installed. If not, it installs it. This will also install it if it is not already present. Next, it will query Microsoft for a list of missing updates. If there are no updates, then the script exits with an error code 0. If there are updates, it will proceed to install them. There was one problem I ran into when writing this script. It did not have sufficient privileges to install the updates. It needed to be run-as-administrator. The workaround for this is to add the account the script is run under to the administrators group on the local machine, which is what the script does. After adding to the administrators group, it installs the updates, while suppressing a reboot. After this is finished, it removes the user from the administrators group. There are four conditions it will then check for to see if a reboot is pending. If it is pending, then the script will initiate a reboot via SCCM if the -SCCM switch is in the parameters field, and it instructs SCCM to rerun the same task. If there is not a pending reboot, then the script checks for additional updates and installs them.

To implement it in SCCM, I used a Run PowerShell Script task sequence. The entire script below was pasted into the Edit Script field of the Enter a PowerShell Script:. I did also use the -SCCM parameter. he Run this step as the following account was also selected that uses the build account.



You can download the script from my GitHub site.


 <#  
      .SYNOPSIS  
           Install Windows Updates  
        
      .DESCRIPTION  
           This script uses the PSWindowsUpdate module to install the latest windows updates. It also makes sure the latest version of the module is installed. It is designed to run in SCCM, MDT, and in a deployment.  
        
      .PARAMETER SCCM  
           This specifies for the script to use the Microsoft.SMS.TSEnvironment comobject for managing the reboot and re-execution of the Windows Update Task  
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.142  
           Created on:       8/29/2019 7:22 AM  
           Created by:       Mick Pletcher  
           Filename:         InstallWindowsUpdates.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [switch]$SCCM  
 )  
 function Enable-Reboot {  
 <#  
      .SYNOPSIS  
           Reboot Machine  
        
      .DESCRIPTION  
           This function will reboot the machine. If the SCCM switch is defined, it will use the task sequence environmental variables to reboot the machine and restart the task sequence.   
        
      .NOTES  
           Additional information about the function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      If ($SCCM.IsPresent) {  
           $TaskSequence = New-Object -ComObject Microsoft.SMS.TSEnvironment  
           #Rerun this task when the reboot finishes   
           $TaskSequence.Value('SMSTSRetryRequested') = $true  
           #Reboot the machine when this command line task sequence finishes   
           $TaskSequence.Value('SMSTSRebootRequested') = $true  
      } else {  
           Restart-Computer -Force  
      }  
 }  
   
 Import-Module PowerShellGet  
 Import-Module -Name PSWindowsUpdate -ErrorAction SilentlyContinue  
 #Get the version of PSWindowsUpdate that is currently installed  
 $InstalledVersion = (Get-InstalledModule -Name PSWindowsUpdate).Version.ToString()  
 #Get the current version of PSWindowsUpdate that is available in the PSGallery  
 $PSGalleryVersion = (Find-Module -Name PSWindowsUpdate).Version.ToString()  
 #Uninstall and install PSWindowsUpdate module if the installed version does not match the version in PSGallery  
 If ($InstalledVersion -ne $PSGalleryVersion) {  
      Install-Module -Name PSWindowsUpdate -Force  
 }  
 #Get the list of available windows updates  
 $Updates = Get-WindowsUpdate  
 If ($Updates -ne $null) {  
      $NewUpdates = $true  
      Do {  
           #Add $AdminUser to Administrators group  
           Add-LocalGroupMember -Group Administrators -Member ($env:USERDOMAIN + '\' + $env:USERNAME)  
           #Install windows updates  
           Install-WindowsUpdate -AcceptAll -IgnoreReboot -Confirm:$false  
           #Remove $AdminUser from the Administrators group  
           Remove-LocalGroupMember -Group Administrators -Member ($env:USERDOMAIN + '\' + $env:USERNAME)  
           #Component Based Reboot   
           If ((Get-ChildItem "REGISTRY::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -ErrorAction SilentlyContinue) -ne $null) {  
                Enable-Reboot  
                $NewUpdates = $false  
           #Windows Update Reboot   
           } elseif ((Get-Item -Path "REGISTRY::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue) -ne $null) {  
                Enable-Reboot  
                $NewUpdates = $false  
           #Pending Files Rename Reboot   
           } elseif ((Get-ItemProperty -Path "REGISTRY::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue) -ne $null) {  
                Enable-Reboot  
                $NewUpdates = $false  
           #Pending SCCM Reboot   
           } elseif ((([wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities").DetermineIfRebootPending().RebootPending) -eq $true) {  
                Enable-Reboot  
                $NewUpdates = $false  
           }  
           #If no pending reboot, then check for new updates  
           If ($NewUpdates -eq $true) {  
                #Check for new windows updates  
                $Updates = Get-WindowsUpdate  
                #No reboot was required from last installed updates, so check if new updates are available and end loop if not  
                If ($Updates -eq $null) {  
                     $NewUpdates -eq $false  
                }  
           }  
      } While ($NewUpdates -eq $true)  
 } else {  
      Exit 0  
 }  
   

21 August 2019

Extract SCCM WIM from ISO and Configure for WDS via PowerShell

One issue, more like a time-waster, I have had as we are migrating to SCCM from MDT is getting the boot image on the WDS server. SCCM is not configured to manage WDS because we use it for other things, so we manually upload the WIM. SCCM creates an ISO that needs to be mounted to extract the WIM for WDS. Thanks to this blog post, it is explained. I wanted the steps automated, so I wrote the following PowerShell script that will perform all of the steps needed to extract and configure the WIM.

To use this, populate the full file name in the $File variable. The script will do the rest. It is documented throughout the script so that it is easy to follow. You can download the script from my GitHub site.


 <#  
      .SYNOPSIS  
           Extract and Configure SCCM WIM Boot Image  
        
      .DESCRIPTION  
           This script will extract the WIM file from the ISO boot image generated by SCCM. It then mounts, configures, and unmounts the WIM file so it is ready to push up to WDS.  
        
      .PARAMETER File  
           Filename of the ISO, which includes the full path.  
        
      .NOTES  
           ===========================================================================  
           Created with:    SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.142  
           Created on:      8/21/2019 12:59 PM  
           Created by:      Mick Pletcher  
           Filename:        SCCMBootImage.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [ValidateNotNullOrEmpty()]  
      [string]$File = 'C:\WinPE\SCCM.iso'  
 )  
   
 Import-Module Dism  
 #Extract the name of the directory the $File resides in  
 $Directory = $File.substring(0, $File.LastIndexOf('\'))  
 #Mount and assign drive letter  
 $Drive = ((Mount-DiskImage -ImagePath $File) | Get-Volume).DriveLetter  
 #Delete old Mount directory  
 Remove-Item -Path ($Directory + '\Mount') -Recurse -Force -ErrorAction SilentlyContinue  
 #Create Mount folder to copy WIM contents to  
 New-Item -Path ($Directory + '\Mount') -ItemType Directory -Force  
 #Delete old WIM file  
 Remove-Item -Path ($Directory + '\boot.wim') -ErrorAction SilentlyContinue -Force  
 #Copy boot.WIM file to $Directory  
 Copy-Item -Path ($Drive + ':\sources\boot.wim') -Destination $Directory -Force  
 #Turn off read only  
 Set-ItemProperty -Path ($Directory + '\boot.wim') -Name IsReadOnly -Value $false  
 #Mount the WIM file  
 Mount-WindowsImage -ImagePath ($Directory + '\boot.wim') -Index 1 -Path ($Directory + '\Mount')  
 #Copy data folder to mounted image  
 Copy-Item -Path ($Drive + ':\SMS\data') -Destination ($Directory + '\Mount\sms') -Recurse -Force  
 #Unmount Windows Image  
 Dismount-WindowsImage -Path ($Directory + '\Mount') -Save  
 #Dismount disk image  
 Dismount-DiskImage -ImagePath $File  
 #Delete the old wim if it exists  
 Remove-Item -Path ((Get-ChildItem -Path ($Directory + '\' + ((Get-ChildItem -path $File -ErrorAction SilentlyContinue).Basename) + '.wim')).FullName) -Force -ErrorAction SilentlyContinue  
 #Rename boot.wim to match the basename of the ISO  
 Rename-Item -Path ($Directory + '\boot.wim') -NewName ((Get-ChildItem -Path $File).BaseName + '.wim') -Force  
 #Delete the Mount folder  
 Remove-Item -Path ($Directory + '\Mount') -Recurse -Force -ErrorAction SilentlyContinue  
   

20 August 2019

Batch file wait for process using PowerShell integration

Recently, I wanted a simple batch file to run the ccmsetup.exe file. I could have used PowerShell, but for debugging the parameters, I wanted it quick and easy to modify. One of the issues I had was getting the batch script to wait for the ccmexec.exe to install before proceeding. I saw some batch solutions that seemed to be kind of cumbersome. I decided to write a PowerShell one-liner that would continuously loop until the desired process ended. To do this, I used the following one-liner and pasted it into the batch file after the ccmsetup.exe was triggered. I wrote this so that all you have to do is change the assigned value to the $ProcessName. I included in the script the ability to remove the file extension in the event it is accidentally used. You can see below how I used it in the batch script:




 powershell.exe -executionpolicy bypass -command "&{$ProcessName='ccmsetup';Do {$Process=get-process ($ProcessName.split('.')[0]) -erroraction SilentlyContinue;Start-Sleep -seconds 2} While ($Process -ne $null)}"  

08 August 2019

Verifying SCCM package has updated the content on the distribution point

One of the things I have wrestled with over the years of using SCCM is verifying if the package on the distribution point contains the new content after updating the distribution point(s). I have typically seen that if there is a minor change, such as maybe a line of two of code changed in a PowerShell installer script, it doesn't get updated the first time around.

While working on the migration of the imaging process from MDT to SCCM, it occurred to me that there is a way to verify. I have typically run the update distribution points at least twice to make sure they all got updated. The easy way to verify is to set up a package share in the properties as shown below.


Now you can watch the package located at \\<SCCM Server Name>\<Share name> to see if the changes take place. They will change in real-time as soon as SCCM updates it. If you are in a testing phase and are having to update the distribution point(s) a lot like I am right now, this is a good way to test after each update.

NOTE: There still is not a way to do this with application deployments. It would be nice if the share option was added there! 

02 August 2019

MDT: How to initiate a reboot during a task without corrupting the task sequence

Recently, I have been working on updating several scripts I have written for the build process. One big thing I have wanted is for the script to be able to initiate a reboot without the build process becoming corrupt. An additional functionality I have wanted to implement is to be able to restart the task sequence at the same point it left off before the reboot.

I knew the task sequence reruns the windows update process multiple times, so I started by looking at the ZTIWindowsUpdate.wsf file. While combing through the file, I found the two items used for this process. They are:

  • SMSTSRebootRequested that reboots the machine
  • SMSTSRetryRequested tells the script to rerun the same task. 
I wanted this to be written in PowerShell, so next was figuring out how to access these two MDT environmental variables. After researching, I found that I can load the comobject Microsoft.SMS.TSEnvironment and that will give access to them. The following three lines of code are all that is needed in a PowerShell script to initiate a reboot and/or rerun the same task once it completes. Setting the above-listed variables to $true is what is required. If you just want to rerun the same task, you are not required to initiate the reboot. Once the task is completed, it will rerun again if SMSTSRetryRequested is specified at the end. 


      $TaskSequence = New-Object -ComObject Microsoft.SMS.TSEnvironment  
      #Reboot the machine this command line task sequence finishes  
      $TaskSequence.Value('SMSTSRebootRequested') = $true  
      #Rerun this task when the reboot finishes  
      $TaskSequence.Value('SMSTSRetryRequested') = $true  

18 July 2019

MDT Conditional Reboot

I wrote an article about three years ago on conditional task sequence reboots. It used the built-in reboot task sequence that was initiated only if any of the three conditions were met. The problem was a fourth condition that could not be tested for because a WMI query is the only way to test and MDT conditions do not incorporate WMI.

Recently, I revisited this, and it occurred to me how to incorporate the WMI query after going through the ZTIWindowsUpdate.wsf and seeing how it initiated reboots. I abandoned the built-in reboot and wrote a PowerShell script that can test all four conditions and then connect to the TSEnvironment object to start a reboot.

NOTE: The fourth test depends on the SCCM client already being installed.

The four conditions the script checks for are:

  • Component Based Servicing
  • Windows Updates
  • Pending Files Rename
  • Pending reboot from SCCM installs
The script will iterate through all four conditions. If a condition is met, it will then connect to the TSEnvironment object and request a reboot by setting SMSTSRebootRequested to true. Once the script is finished, the system will reboot and then proceed to the next task.

I also included the commented out SMSTSRetryRequested in the script. This command will cause the task sequence to rerun this script. I included it in here so if you want to take the code from this script and incorporate it into another script that will rerun it after the reboot, it is there. 

The first thing to do is to copy the script to the scripts (%SCRIPTROOT%) directory. As you can see in the screenshot below, I used a Run Command Line task sequence.



The command line is as follows:

 powershell.exe -executionpolicy bypass -file "%SCRIPTROOT%\ZTIConditionalReboot.ps1"  


Finally, here is the script. You can download it from my GitHub site.

 <#  
      .SYNOPSIS  
           Zero Touch Conditional Reboot  
        
      .DESCRIPTION  
           This script will check four flags on the system to see if a reboot is required. If one of the flags is tripped, then this script will initiate a reboot in MDT so that will come back up and start at the proceeding task. I have included the commented out SMSTSRetryRequested in the script so if you want to incorporate the code from this script into another one that will need to be rerun again once the reboot completes.   
        
      .NOTES  
           ===========================================================================  
           Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.142  
           Created on:       7/12/2019 2:53 PM  
           Created by:       Mick Pletcher  
           Organization:     Waller Lansden Dortch & Davis, LLP.  
           Filename:         ZTIConditionalReboot.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param ()  
   
 function Enable-Reboot {  
 <#  
      .SYNOPSIS  
           Request MDT Reboot  
        
      .DESCRIPTION  
           A detailed description of the Enable-Reboot function.  
 #>  
        
      [CmdletBinding()]  
      param ()  
        
      $TaskSequence = New-Object -ComObject Microsoft.SMS.TSEnvironment  
      #Reboot the machine this command line task sequence finishes  
      $TaskSequence.Value('SMSTSRebootRequested') = $true  
      #Rerun this task when the reboot finishes  
      #$TaskSequence.Value('SMSTSRetryRequested') = $true  
 }  
   
 #Component Based Reboot  
 If ((Get-ChildItem "REGISTRY::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -ErrorAction SilentlyContinue) -ne $null) {  
      Enable-Reboot  
 #Windows Update Reboot  
 } elseif ((Get-Item -Path "REGISTRY::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue) -ne $null) {  
      Enable-Reboot  
 #Pending Files Rename Reboot  
 } elseif ((Get-ItemProperty -Path "REGISTRY::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue) -ne $null) {  
      Enable-Reboot  
 #Pending SCCM Reboot  
 } elseif ((([wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities").DetermineIfRebootPending().RebootPending) -eq $true) {  
      Enable-Reboot  
 } else {  
      Exit 0  
 }  
   


11 June 2019

Fixing Do you want to run this file? during SCCM Deployment

Over the past two months, I deployed the Windows 10 1809 to all Windows 10 machines. We got through 80% of the machines with successful deployments until we reached those last 20% where they did not have enough disk space for both downloading the package and installing it. The package and install require roughly 15 gigs of space, 5 gigs for the package and 10 gigs for the installation.

We changed the distribution points option to run the program from the distribution point to drop down the 15 gig requirement to 10 gigs, which also significantly reduced the number of machines without enough space.


Once we made that change, systems started getting the message shown below. This caused the package to stall since there was no one to click run.



To get around this issue, we added the FQDN of each distribution point to the intranet trusted sites via GPO. The FQDN is added like shown here: \\<SCCMServer.contoso.com>\ and set as security zone 1. This fixed that issue. 

06 June 2019

Configuring Power Scheme with a PowerShell One-Liner

Recently, we decided to change the power scheme on machines during the build. This can be quickly done using the powercfg.exe, but I wanted to be sure it always set correctly. Plus, the GUID associated with a power scheme can be different, so I wanted to specify the power scheme by the name.

This PowerShell one-liner will set the power scheme on a machine to the scheme defined in the variable $Setting. If you do a powercfg.exe /l, you will see the name displayed to the right of the GUID in parenthesis. That is what you define in the above variable. The one-liner will then query powercfg to check if it matches the $Setting variable. If it does, it exits with an error code 0. If it does not match, then it sets the power scheme to the GUID from the query and then rechecks to make sure the setting was configured. If it still does not match, then it exits with an error code 1. 

To use this in a one-liner, you need to define the $Setting inside the one-liner below. This may differ on machines, so do the above query to see what is defined in your environment. Place this one-liner in a command line task sequence and you are done.


 powershell.exe -executionpolicy bypass -command "&{$Setting='Balanced';$Output = powercfg.exe /l | Where-Object {$_ -like ('*' + $Setting + '*')};If ($Output.Contains('*') -eq $true) {Write-Host ($Setting + [char]32 + 'is configured');Exit 0} else {$Output = powercfg.exe /s $output.split(' ')[3]; $Output = powercfg.exe /l | Where-Object {$_ -like ('*' + $Setting + '*')};If ($Output.Contains('*') -eq $true) {Write-Host ($Setting + [char]32 + 'Powercfg is configured');Exit 0} else {Write-Host 'Powercfg failed';Exit 1}}}"  

Below is a pic of what it looks like when used in a Run Command Line task sequence. IMO, it makes managing PowerShell scripts easier when they are contained within the task sequence.


15 April 2019

Configuring Wake-On-LAN for Dell Systems

If you have been wanting to wake your Dell systems up from sleep, hibernate, or shutdown states, this is how you do it. Starting out with this article from Dell, I got the list of things needed to set up the system for WOL. There are three areas that have to be configured on Dell systems, at least for the systems we have which range from the Optiplex 990 to the Latitude 7490. The areas are BIOS, advanced NIC, and power management settings. This site helped with the final setting to disable fast startup, which is required. WOL did not work on our systems until I implemented this final setting.

Before implementing this baseline, you will need to make sure Dell Command | Configure is installed on all systems. To ensure this, I have it deployed as an application to all Dell systems. Dell Command | Configure is what the baseline PowerShell scripts use to query and configure the BIOS settings. I also made a collection called All Dell Systems since we also have a few Microsoft Surfaces.

NOTE: This was created on April 15, 2019. New Dell models and BIOS updates are constantly released. It is likely there will be changes that need to be made in the future to these scripts to work with those updates.

The Wake-On-LAN Compliance item is set up to use a script that returns a Boolean value as shown below.


The discovery script is the following PowerShell script:


 ##Find Dell Command | Configure for 64-bit  
 $CCTK = Get-ChildItem -Path ${env:ProgramFiles(x86)}, $env:ProgramFiles -Filter cctk.exe -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.Directory -like '*x86_64*'}  
 ##Get all available Dell Command | Configure commands for current system  
 $Commands = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName -h} -ErrorAction SilentlyContinue  
 ##Configure BIOS --wakeonlan=enable  
 #Test if wakeonlan exists on current system  
 If ($Commands -like '*wakeonlan*') {  
      [string]$WakeOnLANSetting = 'wakeonlan=enable'  
      [string]$Output = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName --wakeonlan} -ErrorAction SilentlyContinue  
      If ($Output -ne $WakeOnLANSetting) {  
           $WakeOnLAN = $false  
      } else {  
           $WakeOnLAN = $true  
      }  
 }  
 ##Configure BIOS --deepsleepctrl=disable  
 #Test if deepsleepctrl exists on current system  
 If ($Commands -like '*deepsleepctrl*') {  
      [string]$DeepSleepCtrlSetting = 'deepsleepctrl=disable'  
      [string]$Output = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName --deepsleepctrl} -ErrorAction SilentlyContinue  
      If ($Output -ne $DeepSleepCtrlSetting) {  
           $DeepSleepCtrl = $false  
      } else {  
           $DeepSleepCtrl = $true  
      }  
 }  
 ##Configure BIOS --blocks3=disable  
 #Test if blocks3 exists on current system  
 If ($Commands -like '*blocks3*') {  
      [string]$BlockS3Setting = 'blocks3=disable'  
      [string]$Output = Invoke-Command -ScriptBlock { c:\Windows\system32\cmd.exe /c $CCTK.FullName --blocks3} -ErrorAction SilentlyContinue  
      If ($Output -ne $BlockS3Setting) {  
           $BlockS3 = $false  
      } else {  
           $BlockS3 = $true  
      }  
 }  
 ##Configure BIOS --cstatesctrl=disable  
 #Test if cstatesctrl exists on current system  
 If ($Commands -like '*cstatesctrl*') {  
      [string]$CStateCTRLSetting = 'cstatesctrl=disable'  
      [string]$Output = Invoke-Command -ScriptBlock { c:\Windows\system32\cmd.exe /c $CCTK.FullName --cstatesctrl} -ErrorAction SilentlyContinue  
      If ($Output -ne $CStateCTRLSetting) {  
           $CStateCTRL = $false  
      } else {  
           $CStateCTRL = $true  
      }  
 }  
 ##Disable Energy Efficient Ethernet  
 #Energy Efficient Ethernet disable registry value  
 $RegistryValue = '0'  
 #Find ethernet adapter  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter | Where-Object {$_.DisplayName -like '*Efficient Ethernet*'}).DisplayName  
 #Test for presence of Energy-Efficient Ethernet  
 If ($DisplayName -like '*Efficient Ethernet*') {  
      [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
      If ($CurrentState -ne $RegistryValue) {  
           $EnergyEfficientEthernet = $false  
      } else {  
           $EnergyEfficientEthernet = $true  
      }  
 }  
 ##Enable Wake on Magic Packet  
 $State = 'Enabled'  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter | Where-Object {$_.DisplayName -like '*Magic Packet*'}).DisplayName  
 #Test if Magic Packet exists  
 If ($DisplayName -like '*Magic Packet*') {  
      [string]$CurrentState = (Get-NetAdapterPowerManagement -Name $Adapter).WakeOnMagicPacket  
      If ($CurrentState -ne $State) {  
           $WakeOnMagicPacket = $false  
      } else {  
           $WakeOnMagicPacket = $true  
      }  
 }  
 ##Disable Shutdown Wake-On-Lan  
 $RegistryValue = '0'  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter -ErrorAction SilentlyContinue | Where-Object {$_.DisplayName -eq 'Shutdown Wake-On-Lan'}).DisplayName  
 If ($DisplayName -eq 'Shutdown Wake-On-Lan') {  
      [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
      If ($CurrentState -ne $RegistryValue) {  
           $ShutdownWakeOnLAN = $false  
      } else {  
           $ShutdownWakeOnLAN = $true  
      }  
 }  
 ##Enable Allow the computer to turn off this device  
 $KeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\'  
 #Test if KeyPath exists  
 If ((Test-Path $KeyPath) -eq $true) {  
      $PnPValue = 256  
      $Adapter = Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}  
      foreach ($Entry in (Get-ChildItem $KeyPath -ErrorAction SilentlyContinue).Name) {  
           If ((Get-ItemProperty REGISTRY::$Entry).DriverDesc -eq $Adapter.InterfaceDescription) {  
                $Value = (Get-ItemProperty REGISTRY::$Entry).PnPCapabilities  
                If ($Value -ne $PnPValue) {  
                     $PowerManagement = $false  
                } else {  
                     $PowerManagement = $true  
                }  
           }  
      }  
 }  
 ##Disable Fast Startup  
 $KeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power"  
 #Test if KeyPath exists  
 If ((Test-Path -Path ('REGISTRY::' + $KeyPath)) -eq $true) {  
      If ((Get-ItemProperty -Path ('REGISTRY::' + $KeyPath)).HiberbootEnabled -eq 0) {  
           $FastStartup = $false  
      } else {  
           $FastStartup = $true  
      }  
 }  
 #Write-Host 'Wake-On-LAN:'$WakeOnLAN  
 #Write-Host 'Deep Sleep Control:'$DeepSleepCtrl  
 #Write-Host 'BlockS3:'$BlockS3  
 #Write-Host 'CState Control:'$CStateCTRL  
 #Write-Host 'Energy Efficient Ethernet:'$EnergyEfficientEthernet  
 #Write-Host 'Wake-On-Magic-Packet:'$WakeOnMagicPacket  
 #Write-Host 'Shutdown Wake-On-LAN:'$ShutdownWakeOnLAN  
 #Write-Host 'Allow Computer to Turn Off this Device:'$PowerManagement  
 If ((($WakeOnLAN -eq $null) -or ($WakeOnLAN -eq $true)) -and ($FastStartup -eq $false) -and (($DeepSleepCtrl -eq $null) -or ($DeepSleepCtrl -eq $true)) -and (($BlockS3 -eq $null) -or ($BlockS3 -eq $true)) -and (($CStateCTRL -eq $null) -or ($CStateCTRL -eq $true)) -and (($EnergyEfficientEthernet -eq $null) -or ($EnergyEfficientEthernet -eq $true)) -and (($WakeOnMagicPacket -eq $null) -or ($WakeOnMagicPacket -eq $true)) -and (($ShutdownWakeOnLAN -eq $null) -or ($ShutdownWakeOnLAN -eq $true)) -and (($PowerManagement -eq $null) -or ($PowerManagement -eq $true))) {  
      echo $true  
 } else {  
      echo $false  
 }  
   

The remediation script is as follows:


 ##Find Dell Command | Configure for 64-bit  
 $CCTK = Get-ChildItem -Path ${env:ProgramFiles(x86)}, $env:ProgramFiles -Filter cctk.exe -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.Directory -like '*x86_64*'}  
 ##Get all available Dell Command | Configure commands for current system  
 $Commands = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName -h} -ErrorAction SilentlyContinue  
 ##Configure BIOS --wakeonlan=enable  
 #Test if wakeonlan exists on current system  
 If ($Commands -like '*wakeonlan*') {  
      [string]$WakeOnLANSetting = 'wakeonlan=enable'  
      [string]$Output = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName --wakeonlan} -ErrorAction SilentlyContinue  
      If ($Output -ne $WakeOnLANSetting) {  
           $ErrCode = (Start-Process -FilePath $CCTK.FullName -ArgumentList ('--' + $WakeOnLANSetting) -Wait -Passthru).ExitCode  
           If ($ErrCode -eq 0) {  
                $WakeOnLAN = $true  
           } elseif ($ErrCode -eq 119) {  
                $WakeOnLAN = $true  
           } else {  
                $WakeOnLAN = $false  
           }  
           Remove-Variable -Name ErrCode  
      } else {  
           $WakeOnLAN = $true  
      }  
      Remove-Variable -Name WakeOnLANSetting  
      Remove-Variable -Name Output  
 }  
 ##Configure BIOS --deepsleepctrl=disable  
 #Test if deepsleepctrl exists on current system  
 If ($Commands -like '*deepsleepctrl*') {  
      [string]$DeepSleepCtrlSetting = 'deepsleepctrl=disable'  
      [string]$Output = Invoke-Command -ScriptBlock {c:\Windows\system32\cmd.exe /c $CCTK.FullName --deepsleepctrl} -ErrorAction SilentlyContinue  
      If ($Output -ne $DeepSleepCtrlSetting) {  
           $ErrCode = (Start-Process -FilePath $CCTK.FullName -ArgumentList ('--' + $DeepSleepCtrlSetting) -Wait -Passthru).ExitCode  
           If ($ErrCode -eq 0) {  
                $DeepSleepCtrl = $true  
           } elseif ($ErrCode -eq 119) {  
                $DeepSleepCtrl = $true  
           } else {  
                $DeepSleepCtrl = $false  
           }  
           Remove-Variable -Name ErrCode  
      }  
      Remove-Variable -Name DeepSleepCtrlSetting  
      Remove-Variable -Name Output  
 }  
 ##Configure BIOS --blocks3=disable  
 #Test if blocks3 exists on current system  
 If ($Commands -like '*blocks3*') {  
      [string]$BlockS3Setting = 'blocks3=disable'  
      [string]$Output = Invoke-Command -ScriptBlock { c:\Windows\system32\cmd.exe /c $CCTK.FullName --blocks3} -ErrorAction SilentlyContinue  
      If ($Output -ne $BlockS3Setting) {  
           $ErrCode = (Start-Process -FilePath $CCTK.FullName -ArgumentList ('--' + $BlockS3Setting) -Wait -Passthru).ExitCode  
           If ($ErrCode -eq 0) {  
                $BlockS3 = $true  
           } elseif ($ErrCode -eq 119) {  
                $BlockS3 = $true  
           } else {  
                $BlockS3 = $false  
           }  
           Remove-Variable -Name ErrCode  
      } else {  
           $BlockS3 = $true  
      }  
      Remove-Variable -Name BlockS3Setting  
      Remove-Variable -Name Output  
 }  
 ##Configure BIOS --cstatesctrl=disable  
 #Test if cstatesctrl exists on current system  
 If ($Commands -like '*cstatesctrl*') {  
      [string]$CStateCTRLSetting = 'cstatesctrl=disable'  
      [string]$Output = Invoke-Command -ScriptBlock { c:\Windows\system32\cmd.exe /c $CCTK.FullName --cstatesctrl} -ErrorAction SilentlyContinue  
      If ($Output -ne $CStateCTRLSetting) {  
           $ErrCode = (Start-Process -FilePath $CCTK.FullName -ArgumentList ('--' + $CStateCTRLSetting) -Wait -Passthru).ExitCode  
           If ($ErrCode -eq 0) {  
                $CStateCTRL = $true  
           } elseif ($ErrCode -eq 119) {  
                $CStateCTRL = $true  
           } else {  
                $CStateCTRL = $false  
           }  
           Remove-Variable -Name ErrCode  
      } else {  
           $CStateCTRL = $true  
      }  
      Remove-Variable -Name CStateCTRLSetting  
      Remove-Variable -Name Output  
 }  
 ##Disable Energy Efficient Ethernet  
 #Energy Efficient Ethernet disable registry value  
 $RegistryValue = '0'  
 #Find ethernet adapter  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter | Where-Object {$_.DisplayName -like '*Efficient Ethernet*'}).DisplayName  
 #Test for presence of Energy-Efficient Ethernet  
 If ($DisplayName -like '*Efficient Ethernet*') {  
      [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
      If ($CurrentState -ne $RegistryValue) {  
           Set-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName -RegistryValue $RegistryValue  
           Do {  
                Try {  
                     [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
                     $Err = $false  
                } Catch {  
                     $Err = $true  
                }  
           } While ($Err -eq $true)  
           If ($RegistryValue -eq $CurrentState) {  
                $EnergyEfficientEthernet = $true  
           } else {  
                $EnergyEfficientEthernet = $false  
           }  
           Remove-Variable -Name Err  
      } else {  
           $EnergyEfficientEthernet = $true  
      }  
      Remove-Variable -Name RegistryValue  
      Remove-Variable -Name Adapter  
      Remove-Variable -Name DisplayName  
      Remove-Variable -Name CurrentState  
 }  
 ##Enable Wake on Magic Packet  
 $State = 'Enabled'  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter | Where-Object {$_.DisplayName -like '*Magic Packet*'}).DisplayName  
 #Test if Magic Packet exists  
 If ($DisplayName -like '*Magic Packet*') {  
      [string]$CurrentState = (Get-NetAdapterPowerManagement -Name $Adapter).WakeOnMagicPacket  
      If ($CurrentState -ne $State) {  
           Set-NetAdapterPowerManagement -Name $Adapter -WakeOnMagicPacket $State  
           Do {  
                Try {  
                     [string]$CurrentState = (Get-NetAdapterPowerManagement -Name $Adapter).WakeOnMagicPacket  
                     $Err = $false  
                } Catch {  
                     $Err = $true  
                }  
           } While ($Err -eq $true)  
           If ($State -eq $CurrentState) {  
                $WakeOnMagicPacket = $true  
           } else {  
                $WakeOnMagicPacket = $false  
           }  
           Remove-Variable -Name Err  
      } else {  
           $WakeOnMagicPacket = $true  
      }  
      Remove-Variable -Name State  
      Remove-Variable -Name Adapter  
      Remove-Variable -Name DisplayName  
      Remove-Variable -Name CurrentState  
 }  
 ##Disable Shutdown Wake-On-Lan  
 $RegistryValue = '0'  
 $Adapter = (Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}).Name  
 $DisplayName = (Get-NetAdapterAdvancedProperty -Name $Adapter -ErrorAction SilentlyContinue | Where-Object {$_.DisplayName -eq 'Shutdown Wake-On-Lan'}).DisplayName  
 If ($DisplayName -eq 'Shutdown Wake-On-Lan') {  
      [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
      If ($CurrentState -ne $RegistryValue) {  
           Set-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName -RegistryValue $RegistryValue  
           Do {  
                Try {  
                     [string]$CurrentState = (Get-NetAdapterAdvancedProperty -Name $Adapter -DisplayName $DisplayName).RegistryValue  
                     $Err = $false  
                } Catch {  
                     $Err = $true  
                }  
           } While ($Err -eq $true)  
           If ($RegistryValue -eq $CurrentState) {  
                $ShutdownWakeOnLAN = $true  
           } else {  
                $ShutdownWakeOnLAN = $false  
           }  
           Remove-Variable -Name Err  
      } else {  
           $ShutdownWakeOnLAN = $true  
      }  
      Remove-Variable -Name RegistryValue  
      Remove-Variable -Name Adapter  
      Remove-Variable -Name DisplayName  
      Remove-Variable -Name CurrentState  
 }  
 ##Enable Allow the computer to turn off this device  
 $KeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\'  
 #Test if KeyPath exists  
 If ((Test-Path $KeyPath) -eq $true) {  
      $PnPValue = 256  
      $Adapter = Get-NetAdapter | Where-Object {($_.Status -eq 'Up') -and ($_.PhysicalMediaType -eq '802.3')}  
      foreach ($Entry in (Get-ChildItem $KeyPath -ErrorAction SilentlyContinue).Name) {  
           If ((Get-ItemProperty REGISTRY::$Entry).DriverDesc -eq $Adapter.InterfaceDescription) {  
                $Value = (Get-ItemProperty REGISTRY::$Entry).PnPCapabilities  
                If ($Value -ne $PnPValue) {  
                     Set-ItemProperty -Path REGISTRY::$Entry -Name PnPCapabilities -Value $PnPValue -Force  
                     Disable-PnpDevice -InstanceId $Adapter.PnPDeviceID -Confirm:$false  
                     Enable-PnpDevice -InstanceId $Adapter.PnPDeviceID -Confirm:$false  
                     $Value = (Get-ItemProperty REGISTRY::$Entry).PnPCapabilities  
                }  
                If ($Value -eq $PnPValue) {  
                     $PowerManagement = $true  
                } else {  
                     $PowerManagement = $false  
                }  
                Remove-Variable -Name Value  
           }  
      }  
      Remove-Variable -Name PnPValue  
      Remove-Variable -Name Adapter  
      Remove-Variable -Name KeyPath  
 }  
 ##Disable Fast Startup  
 $KeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power"  
 #Test if KeyPath exists  
 If ((Test-Path -Path ('REGISTRY::' + $KeyPath)) -eq $true) {  
      Set-ItemProperty -Path ('REGISTRY::' + $KeyPath) -Name 'HiberbootEnabled' -Value 0  
      If ((Get-ItemProperty -Path ('REGISTRY::' + $KeyPath)).HiberbootEnabled -eq 0) {  
           $FastStartup = $false  
      } else {  
           $FastStartup = $true  
      }  
 }  
 #Write-Host 'Wake-On-LAN:'$WakeOnLAN  
 #Write-Host 'Deep Sleep Control:'$DeepSleepCtrl  
 #Write-Host 'BlockS3:'$BlockS3  
 #Write-Host 'CState Control:'$CStateCTRL  
 #Write-Host 'Energy Efficient Ethernet:'$EnergyEfficientEthernet  
 #Write-Host 'Wake-On-Magic-Packet:'$WakeOnMagicPacket  
 #Write-Host 'Shutdown Wake-On-LAN:'$ShutdownWakeOnLAN  
 #Write-Host 'Allow Computer to Turn Off this Device:'$PowerManagement  
 If ((($WakeOnLAN -eq $null) -or ($WakeOnLAN -eq $true)) -and ($FastStartup -eq $false) -and (($DeepSleepCtrl -eq $null) -or ($DeepSleepCtrl -eq $true)) -and (($BlockS3 -eq $null) -or ($BlockS3 -eq $true)) -and (($CStateCTRL -eq $null) -or ($CStateCTRL -eq $true)) -and (($EnergyEfficientEthernet -eq $null) -or ($EnergyEfficientEthernet -eq $true)) -and (($WakeOnMagicPacket -eq $null) -or ($WakeOnMagicPacket -eq $true)) -and (($ShutdownWakeOnLAN -eq $null) -or ($ShutdownWakeOnLAN -eq $true)) -and (($PowerManagement -eq $null) -or ($PowerManagement -eq $true))) {  
      echo $true  
 } else {  
      echo $false  
 }  
   


Finally, the compliance rule is as follows:


You may wonder why I included Remove-Variable cmdlets. I used those when I was debugging so it was easier to track variable values.

For the configuration baseline, I have it configured as shown below:


11 April 2019

Ensuring Compliance When Deploying a Self-Updating Application

In my list of recent security projects, I needed to ensure certain applications are present on systems by using SCCM application deployment. One of those applications was Dell Command | Configure. The issue with this application is the Dell Command | Update will update the application which in turn would register it as not installed to SCCM, thereby kicking off the installation again. That, in turn, would downgrade the application. There are three built-in options in SCCM to choose from that indicate whether an application is installed or not. Those are application GUID, files, and registry. The GUID typically changes every time an app is upgraded and the files and registry can change too. Luckily, this application never changes its name in the programs and features. The version field is typically what changes unless it is a significant upgrade.

The fourth option for confirming if an app is installed is custom method detection where you use a PowerShell script. That is the option I have used to make sure the Dell Command | Configure is registered as installed, no matter the version it has updated to. The following script can be used for this purpose. As you can see, I assigned the application name exactly as it appears in the programs and features to the variable $Application. If a company does include the version in the application name, then you can wildcard the version portion. Say the example below was Dell Command | Configure 3.1, you could use Dell Command | Configure for $Application and it would still find the app. You might wonder why I am outputting the name of the application. All SCCM wants to see is a string output which it interprets as installed. If no output occurs, then SCCM interprets that as not installed. 


 $Application = 'Dell Command | Configure'  
 $InstalledApps = Get-ChildItem -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" -Recurse | ForEach-Object {$_.GetValue('DisplayName')}  
 If (@($InstalledApps) -like ('*' + $Application + '*')) {  
      Write-Host (@($InstalledApps) -like $Application)  
 }  

01 April 2019

Running an SCCM Package via PowerShell and Command Line

While working on a new compliance policy, I ran into a lot of hurdles that needed to be resolved. One of those hurdles was executing an SCCM package via PowerShell. Using the WMIExplorer, I was able to locate a method that allows you to execute an SCCM package as shown below.


Once I located the namespace, class, and method, I needed to find out the name of the package in SCCM that I wanted to execute. To do this, the easiest method is to perform a WMI query in PowerShell on the advertised machine. The query is:

 Get-WmiObject -Class ccm_program -Namespace root\ccm\ClientSDK  

The results will display all advertised programs to that machine. From the results, locate the package you are wanting to execute by the Name, which will match the name in the SCCM console. Once you have found the package, take note of the PackageID and ProgramID, as these are the two items needed to execute the package via PowerShell.

The syntax of calling this from PowerShell is as follows, where the Program ID and Package ID are substituted with the appropriate data from the WMI query:

 ([wmiclass]'root\ccm\ClientSDK:CCM_ProgramsManager').ExecuteProgram('<ProgramID>','<Package ID>')  

The following PowerShell command line method will allow you to call this from the command line, where the Program ID and Package ID are substituted with the appropriate data from the WMI query:

 powershell.exe -executionpolicy bypass -command "&{([wmiclass]'root\ccm\ClientSDK:CCM_ProgramsManager').ExecuteProgram('<ProgramID>','<Package ID>')}"  

When executing the package, there will be output. If you allow for the default output, it can take an extended period of time to gather the information. Specifying a specific field will dramatically speed up the execution time.

NOTE: One thing I learned after discovering this is that SCCM Compliance rules cannot execute this WMI method. I will be writing a separate blog on that in the future as I just finished the compliance policy that goes into detail on executing an SCCM package. 

27 March 2019

Initiating an SCCM Compliance Check via PowerShell

Recently, I have been working on Configuration Baselines for security purposes. While doing so, two of my baselines required remediation that takes longer than 1 minute. I do not recall where I read it, but I believe the timeout for a compliance check is 1 minute. If the compliance remediation takes longer than 1 minute, then the baseline is designated as non-compliant until the next compliance check is run. This snippet of code can also be used in any other instance where the configuration manager client is installed.

To expedite this process, I tracked down how to execute a compliance check through PowerShell so that it can be executed at the end of the remediation script. Thanks to Trevor Sullivan's blog post, I was able to grab and modify the code from it to make into an easy to use code snippet within a Baseline remediation PowerShell script.

To make this easier, I wrote the script as two lines. The first line is where you specify the name of the baseline. As you can see in the pic below of a partial list of baseline configurations, the names of those baselines are what you need to specify for the variable $Name. The code snippet at the bottom shows using the Pending Reboot name to trigger a compliance check for that baseline. 



Once you have specified the name of the baseline, you can then copy and paste both lines at the bottom of the PowerShell remediation script so that a baseline configuration is triggered at the end of the remediation. Here is the code snippet: 


 $Name='Pending Reboot'  
 ([wmiclass]"root\ccm\dcm:SMS_DesiredConfiguration").TriggerEvaluation(((Get-WmiObject -Namespace root\ccm\dcm -class SMS_DesiredConfiguration | Where-Object {$_.DisplayName -eq $Name}).Name), ((Get-WmiObject -Namespace root\ccm\dcm -class SMS_DesiredConfiguration | Where-Object {$_.DisplayName -eq $Name}).Version))  
   

08 March 2019

Bitlocker Active Directory Recovery Password Backup Compliance

Recently, we had an issue of some machines not backing up the Bitlocker recovery password to active directory, even with the GPO in place. They ended up being offline while the bitlocker process took place. Plus, some of the systems in AD had multiple entries, which can be cumbersome. To mitigate this issue, I have implemented an SCCM Configuration Baseline that makes sure the Bitlocker recovery password is backed up to AD and that it is the only recovery password present.

NOTE: This script is being used in an environment that only encrypts the %systemdrive%. If your environment encrypts other items such as flash drives, removable HDDs, and etc, you will need to modify these scripts to meet your environment needs. It will delete those items from active directory also. 

To do this, I first implemented a baseline that enabled the RSAT active directory feature in Windows 10. This is needed so the scripts can query and write to AD. Once this was deployed, I created the BitLocker Recovery Password Backup configuration item.


 Platforms must be set to Windows 10 as some of the cmdlets used in the scripts only exist in that OS and newer.



The script returns a true or false value that dictates if remediation is needed.


The first script queries the local system and AD for the recovery passwords to compare. If they match and only one is in AD, then True is returned that dictates the system is in compliance. False is returned if there is no password stored in AD, there is more than one password in AD, or the wrong password is stored in AD.

Here is the discovery script:

 $RecoveryKey = (Get-BitLockerVolume -MountPoint $env:SystemDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}  
 $ADBitLockerRecoveryKey = (Get-ADObject -Filter {objectclass -eq 'msFVE-RecoveryInformation'} -SearchBase (Get-ADComputer -Identity $env:COMPUTERNAME).DistinguishedName -Properties 'msFVE-RecoveryPassword')  
 If ($ADBitLockerRecoveryKey -eq $null) {  
      Echo $false  
 } elseif ($ADBitLockerRecoveryKey -isnot [system.Array]) {  
      If (([string]$RecoveryKey.RecoveryPassword).Trim() -eq ([string]$ADBitLockerRecoveryKey.'msFVE-RecoveryPassword').Trim()) {  
           Echo $true  
      } else {  
           Echo $false  
      }  
 } elseif ($ADBitLockerRecoveryKey -is [system.Array]) {  
      Echo $false  
 }  


Next comes the remediation script. This is what will be executed if the discovery script returns a False value:



 $RecoveryKey = (Get-BitLockerVolume -MountPoint $env:SystemDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}  
 Write-Host 'Local Recovery Password:'$RecoveryKey.RecoveryPassword  
 $ADBitLockerRecoveryKey = (Get-ADObject -Filter {objectclass -eq 'msFVE-RecoveryInformation'} -SearchBase (Get-ADComputer -Identity $env:COMPUTERNAME).DistinguishedName -Properties 'msFVE-RecoveryPassword')  
 Write-Host '  AD Recovery Password:'$ADBitLockerRecoveryKey.'msFVE-RecoveryPassword'  
 If (($ADBitLockerRecoveryKey -isnot [system.Array]) -and ($ADBitLockerRecoveryKey -ne $null)) {  
      Remove-ADObject -Identity $ADBitLockerRecoveryKey.DistinguishedName -Confirm:$false  
 } elseif ($ADBitLockerRecoveryKey -is [system.Array]) {  
      Foreach ($Key in $ADBitLockerRecoveryKey) {  
           Write-Host 'Removing'$Key.DistinguishedName  
           Remove-ADObject -Identity $Key.DistinguishedName -Confirm:$false  
      }  
 }  
 Backup-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId $RecoveryKey.KeyProtectorId  
 

The final thing to set in the configuration item is the compliance rule as shown below:


Now that the configuration item is created, the configuration baseline must be created and deployed. Here are the screenshots of my configuration baseline that I later deployed out to all laptop systems, which are the systems here that are BitLockered.





07 March 2019

Active Directory PowerShell Module Configuration Baseline

With the recent 1809, RSAT is now integrated into Windows, which is a major plus for the admin side. In my environment, I have the active directory PowerShell module enabled on all machines for two reasons. The first is I use it to move the machine in AD during the build process. The second is that I have an SCCM baseline that makes sure the Bitlocker key matches the one stored in AD. For these, I need the module installed and thankfully it is now just a simple Add-WindowsCapability cmdlet.

I implemented the following baseline that first checks to make sure the Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 feature is enabled. It returns a boolean value of $true if it is Installed and $false if it is Not Present. If $false is returned, then the remediation script will turn on the feature. 

I am going to assume you already know how to setup a configuration item, so I am not going to go through the screen by screen process. This is the main screen of the Item. 



Here is the PowerShell query for checking if it is enabled and returning the $true or $false. 

 If ((Get-WindowsCapability -Online -Name 'Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0').State -eq 'Installed') {Echo $true} elseif ((Get-WindowsCapability -Online -Name 'Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0').State -eq 'NotPresent') {echo $false}  



Here is the remediation script for enabling RSAT AD if it is not enabled.

 Add-WindowsCapability -Online -Name 'Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0'  


Finally, this is the compliance rule that enables the remediation if it is not enabled.


Now to deploy the Configuration Item, the Baseline needs to be created and deployed. This is a very simple procedure. Here are screenshots of my setup of the Baseline.



04 March 2019

Local Administrator Baseline Compliance

One of the issues we have had is some users ending up being in the administrators group. There are circumstances to which we have to sometimes put a user in that group to install an application which is both user and computer-based. It can be easy to forget to take the user back out of that group. We don't allow the end users here to have local administrator privileges for security reasons.

I have finally gotten around to using PowerShell along with the compliance settings in SCCM to manage this issue. To implement a compliance setting to monitor systems where users have local admin privs, I first setup the configuration item. As shown below, I setup the configuration item to look for an integer value, 0 or 1, returned from the PowerShell script. It returns 0 if nothing shows up in the query and a 1 if there are users in the query.

The first step is to create the Configuration Item as shown in the following instructions:

In SCCM under Assets and Compliance-->Compliance Settings-->Configuration Items, click Create Configuration Item from the toolbar above.


In my environment, we are now only Windows 10, so I selected that as the platform.


The next screen will be to create the conditions associated with the configuration item. Under this, you will click New


The next screen is creating the setting. I used the name Local Administrators, the setting is defined by a PowerShell script that returns an integer value of 0 or 1.


The next screen is entering the PowerShell script to query for users that may exist in the group. If there are users in your environment that need to be there by default, you will need to add them to the where-object to exclude from the query. You could also put them in a text file on a UNC share the script could read and compare against.


Here is the script for easy copy and paste.

 If ((Get-LocalGroupMember -Group Administrators | Where-Object {($_.ObjectClass -eq 'User') -and ($_.Name -notlike '*Administrator*')}).Count -gt 0) {Echo 1} else {Echo 0}  

Next comes the Compliance Rules. This is where you specify what the value returned from the query is considered as complying.


This is the specification defined for the rule.



Now that Configuration Items is created, we must create a Baseline that will use the Configuration Item when deployed out to collections.

In SCCM under Assets and Compliance-->Compliance Settings-->Configuration Baselines, click Create Configuration Baseline from the toolbar above.


I used the Name Local Admin. Next, click on Add-->Configuration Items. The following screen will appear:


Select the Local Administrator and click Add. Mine in the pic is slightly different in naming because I already had this created before writing this blog.

Now click OK and the Configuration Baseline will be created. The Baseline is now ready to be deployed out. Select the Local Admin Baseline from the Configuration Baselines and click Deploy. The following screen will appear:


These are the specifications I decided to use. I made the alert to generate if 100% compliance is not met so I know by the next day if someone has local admin. As you can see in the results below, the system I deployed it to is compliant.


I also went into that system and added a user to the administrators group it returned the result of non-compliant when I reran the compliance scan. Another thing that can be done here is to create collections that are based on the compliance and non-compliance of the baseline. This can be done by clicking on the configuration baseline and then right-clicking on the deployment at the bottom. Click on Create New Collection and the options to create the collections by the results will come up as shown below.


If you want to expedite the evaluation time while testing this out, you can go to a system you have deployed this to and open up Configuration Manager from the control panel. Under that, click configurations. If it is not appearing there yet, click refresh and the new baseline should appear. Now that it is displayed there, you can click evaluate at the bottom to run the baseline.


15 February 2019

Loss of Bluetooth Connectivity Resolved via PowerShell

Recently, we ran into the issue of users replacing their keyboard and mouse with Bluetooth devices. What happened was they would lose connectivity and the error below would appear in the event viewer logs.


While researching the issue, we found that the user could open up the laptop that was docked and get connectivity back by hitting any key. The culprit was the Power Management setting of the Bluetooth device. The "Allow the computer to turn off this device to save power" setting disconnected the Bluetooth devices, and because both were the keyboard and mouse, there was no way for them to wake Bluetooth back up. The fix for this was to uncheck the setting as shown below. 


At first, I thought because this was a similar setting as is on the NIC Power Management that I could manipulate it via the registry. I could not find any key that configures this setting. Through more research, I was able to find this solution in a posting on Reddit

I took the script and made it into a one-liner with the Enable variable set to $false in the beginning since it is enabled ($true) by default.  This will allow for the script to be implemented inside a task sequence in MDT or SCCM. 

Here is the script in both a one-liner and regular code. 

PowerShell One-Liner if you want to use this in an MDT or SCCM command line task sequence:
 powershell.exe -executionpolicy bypass -command "&{$Enable=$false;$BTDevice=Get-PnpDevice -Class Bluetooth -InstanceId USB*;$BTDevice | ForEach-Object -Process {$WQL='SELECT * FROM MSPower_DeviceEnable WHERE InstanceName LIKE ' + [char]34 + [char]37 + $([Regex]::Escape($_.PNPDeviceID)) + [char]37 + [char]34;Set-CimInstance -Namespace root\wmi -Query $WQL -Property @{Enable = $Enable} -PassThru};Get-PnpDevice -Class Bluetooth -InstanceId USB* | ForEach-Object -Process {$Test='InstanceName LIKE ' + [char]34 + [char]37 + $([Regex]::Escape($_.PNPDeviceID)) + [char]37 + [char]34;If ((Get-CimInstance -ClassName MSPower_DeviceEnable -Namespace root\wmi -Filter $Test).Enable -eq $Enable) {Write-Host 'Success';Exit 0} else {Write-Host 'Failed';Exit 1}}}"  

PowerShell .PS1 File

 <#  
      .SYNOPSIS  
           Bluetooth Power Management  
        
      .DESCRIPTION  
           This script will enable or disable the Power Management Setting that allows the computer to turn off the Bluetooth device to save power  
        
      .PARAMETER Enable  
           $true will check the Allow the computer to turn off this device to save power. $false will do the opposite. The default has been set to $false since it is originally checked in the OS  
        
      .NOTES  
           ===========================================================================  
           Created with:    SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.142  
           Created on:      2/12/2019 3:20 PM  
           Created by:      Mick Pletcher  
           Filename:        BluetoothPowerState.ps1  
           ===========================================================================  
 #>  
 [CmdletBinding()]  
 param  
 (  
      [ValidateNotNullOrEmpty()]  
      $Enable = $false  
 )  
   
 #$Enable = $false  
 $BTDevice = Get-PnpDevice -Class Bluetooth -InstanceId USB*; $BTDevice | ForEach-Object -Process {  
      $WQL = 'SELECT * FROM MSPower_DeviceEnable WHERE InstanceName LIKE ' + [char]34 + '%' + $([Regex]::Escape($_.PNPDeviceID)) + '%' + [char]34  
      Set-CimInstance -Namespace root\wmi -Query $WQL -Property @{  
           Enable = $Enable  
      } -PassThru  
 }  
 Get-PnpDevice -Class Bluetooth -InstanceId USB* | ForEach-Object -Process {  
      $Test = 'InstanceName LIKE ' + [char]34 + '%' + $([Regex]::Escape($_.PNPDeviceID)) + '%' + [char]34  
      If ((Get-CimInstance -ClassName MSPower_DeviceEnable -Namespace root\wmi -Filter $Test).Enable -eq $Enable) {  
           Write-Host $BTDevice.FriendlyName'Power Management Successfully Configured'  
           Write-Host  
           Exit 0  
      } else {  
           Write-Host $BTDevice.FriendlyName'Power Management Failed to Configure'  
           Exit 1  
      }  
 }