Auto Diskpart and stale entry delete from SCCM during Imaging process

I know many of the build administrators are deploying the Task Sequence on unknown device collection. I purpose and the idea behind it is to do not deploy the task sequence on a production device and prevent accidental data loss.

If the machine is in SCCM collection and we want to run the task sequence on it, we must SCCM Console and do a manual deletion job and wait for a couple of minutes to restart the imaging on the target machine

This is a time-consuming and repetitive task for us. Can we create a way to do this in an automotive way? Like, create the PowerShell Script, which will automatically read the machine's MAC Address and connect to the SCCM database from the WinPE environment for getting all the hostnames to hold by that mac address and delete each.

Also, can we do a diskpart at the same time to avoid further imaging failure? Yes we can create the PowerShell Script and integrate it with Boot Image, which will automatically check whether the machine having an internal storage device attached or not, and based on the results script will perform Diskpart operation, if the internal storage device is faulty or not connected in BIOS, the script will prompt the error.

We can achieve the below business benefits: -

·            Rectify internal Hard Disk Errors and Save imaging time instantly

·            Save the Boot Stick recreation time

·            Avoid multiple restarts unnecessarily

·            Find exact RCA for internal HDD failure and avoid unnecessary troubleshooting

·            Reduce imaging build time as1hrs/imaging

·            Increase tech support productivity

·            Avoid daily repeated and headache tasks

·            Make a user-friendly imaging process

let's do it.......

We must create one txt file which will help us to do the diskpart while executing PowerShell.

this text file includes

 

select disk 0

clean

exit

 or you can use sel disk 0  "0" is representing the number of attached HDD/SSD hard drive. you can change it according to your requirement.

save this text file as dc_diskpart.txt

Second, we have to create one PowerShell script. which include your SCCM Primary site server FQDN and Site code along with the SCCM administrator's username and password.

Create PS1 file and insert the below code into it and save it as Diskpart.PS1

create one folder and keep both the txt and ps1 file in one folder called "SmartDiskPart"

Create SCCM package and distribute on require DPs.

Now, select Boot Image properties and navigate to the Customization tab and add the DiskPart package, and add command line as PowerShell.exe -executionpolicy bypass -file Diskpart.ps1

Boot Image
 

·       PROCEDURE: -

  • Boot the machine from PXE or Boot Media and provide the credentials for further processing.


Password Secure Boot Media

  • Once you enter the Boot media password, the PowerShell script will execute the diskpart program, and ask you for your input as shown below screenshot.

Diskpart through PowerShell

  • If an internal disk drive is not present the script will throw the error as shown in the below screenshot

Smart DiskPart


  • Based on your input, the script will run the next part of the program and goes to the next step (Stale Record management-SCCM). 
This step also asks you for your input as shown in the below screenshot. 

Stale Record management-SCCM
  • Getting your machine mac addresses
Smart DiskPart


  • Based on your machine mac address we are checking the machine in the SCCM database.
MAC Address Check
  • Be there Now we have found your machine in the SCCM database. Don't worry we will clean it..... Once the hostname is deleted from the SCCM database we have created 120 seconds wait time to pause the script and till the SCCM database updates to Task Sequence make available for the machine.
Delete Stale Record

  • Woo!!! Hostname entry deleted from SCCM database.

Stale Entry Delete from SCCM

  • Task Sequence will continue after finishing the PowerShell program execution.

Available Task Sequence on Unknown Collection
  • Once you click on Next, Task Sequence will start execution.
Executing Task Sequence on Unknown Collection


Below is the PowerShell script you have to use for this automation. Enjoy and do let me your feedback.

 

<#

    .SYNOPSIS

   This script will handle Stale Hostname entry(s) management and Diskpart during the Imaging process.

    .DESCRIPTION

     While tech guys are going to image the machines with Boot Media, they should diskpart the machine and wipe all partitions from the internal Hard Disk Drive. Sometimes internal disk having some issues and it’s not getting connected to the laptop and then when tech guys are performing diskpart with select disk 0. The external storage device is getting selected on select disk 0 and the same got formatted mistakenly. If deployed all the production task sequences on Unknown Computers collection. While tech guys are going to image the machines with PXE/Boot Media and if a machine is the part of existing collection and is present in the SCCM database, Task Sequence will fail. Then tech guys need to collect the MAC Address and Serial Number of that machine and provide the same over mail with us to clear the entry from the SCCM database. Based on details shared by Tech Guys, then we need to check the machine on the SCCM database and delete the entry(s) and revert on mail for further processing.

    .NOTES

  =============================================================================================================================================

    Created with:     Windows PowerShell ISE

    Created on:       Tuesday, August 17, 2021 2:05:44 PM

    Created by:       Dashrath Chate

    Organization:     ORG Name here

 =============================================================================================================================================

#>

Add-Type -AssemblyName PresentationFramework

$msgBoxInput =[System.Windows.MessageBox]::Show('Would  you like to Clean the Internal HDD data? If you are performing USMT, DO NOT select Yes','Diskpart Input','YesNo','Information')

switch  ($msgBoxInput)  {

                          'Yes' {

                                 If(Get-wmiobject win32_diskdrive | ? Model -Match 'ata | sata | pata | scsi | sdd')

                                 {diskpart /s x:\sms\PKG\SMS10000\diskpart.txt >>x:\windows\temp\smstslog\diskpart.log}

                                 else                                    {[System.Windows.MessageBox]::Show('No root directory. Drive type could not be determined. Please check the BOIS Settings if Physical Hard Drive is present.','Diskpart Error','OK','Error')}

                                Write-Progress -Activity "DiskPart Utility is cleaning your internal Hard Disk..."

                                }

                          'No'  {

                                }

                        }

 $msgBoxInput =[System.Windows.MessageBox]::Show('Would  you like to clear the STALE record of this machine from SCCM Server? If you have cleared it already then please skip at this time','Stale Record Management-SCCM','YesNo','Information')

switch  ($msgBoxInput)  {

                          'Yes' {

$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path

$log      = "$ScriptDir\clientremoval.log"

$Username="yourdomain\sccmadministrator"

$SecurePassword= ConvertTo-SecureString "Passw0rd here" -AsPlainText -Force

$Cre =New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword

$hostnameout="$ScriptDir\hostnameinput.txt"

$macstore= "$ScriptDir\macstore.txt"

$SMSMPServer = "SCCM_MP_FQDN_HERE"

#$SiteCode = Get-PSDrive -PSProvider CMSITE

#$SMSProvider=$sitecode.SiteServer

#Set-Location "$($SiteCode.Name):\"

(gwmi -class "Win32_NetworkAdapterConfiguration"  | ? IpEnabled -EQ "True" |select MACAddress).MACAddress |Out-File $macstore -Append

Write-Progress -Activity "Getting your Machine MAC ADdressess..."

$date     = Get-Date -Format "dd-MM-yyyy hh:mm:ss"

"---------------------  Script executed on $date (dd-MM-yyyy hh:mm:ss) ---------------------" + "`r`n" | Out-File $log -append

#Import-Module (Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATH) ConfigurationManager.psd1)

$MacAddress=Get-Content $ScriptDir"\macstore.txt"

    ForEach ($hostname in $MacAddress)

{

 (Get-WmiObject -ComputerName $SMSMPServer -Namespace root\sms\site_CMM  -Credential $Cre -Class SMS_R_SYSTEM | Where-Object { $_.MacAddresses[0] -eq $hostname}).name |Out-File $hostnameout -Append

            Write-Progress -Activity "Based on your machines MAC Address we are checking the hostname in SCCM Database..."

            }

$hostnamein=Get-Content $ScriptDir"\hostnameinput.txt"

    ForEach ($client in $hostnamein)

             {

             $CN = Get-WmiObject -cn $SMSMPServer -Namespace root\sms\site_CMM  -Credential $Cre -Class SMS_R_SYSTEM -filter "Name='$client'"

             Write-Progress -Activity "Be there.. Now we have found your machine in SCCM DB. Don't Worry we will clean it..."

             $name=$CN.Name

 if ($name)

    {

        try {

            "$date [INFO]`t $name found in SCCM " | Out-File $log -append

               #Remove-CMDevice -name $client -force

            $CN.delete()

               "$date [INFO]`t $name removed from SCCM " | Out-File $log -append

             Start-Sleep -Seconds 120

            }

        catch

            {

             "$date [INFO]`t $name found in SCCM but unable to delete record.Check further " | Out-File $log -append

         }

    }

 else

    {

    "$date [INFO]`t $client not found in SCCM " | Out-File $log -append}

                 } 

  }

'No'  {

                                 }

                         }

No comments:

Post a Comment

Leave your valuable words here for improve better.