Monday, 30 December 2024

Troubleshooting MDT Integration with Multiple Primaries and Editing the Microsoft.BDD.CM12Actions.mof File

 

Introduction

Microsoft Deployment Toolkit (MDT) and System Center Configuration Manager (SCCM) are powerful tools commonly used together for operating system deployments. However, when integrating MDT with SCCM, especially in environments with multiple primary site servers, issues can arise in task sequences. One such issue occurs when editing the Microsoft.BDD.CM12Actions.mof file to change the site service, leading to errors in MDT integration and task sequence execution.

In this blog, we will explore the challenges faced when MDT integration doesn’t install correctly, particularly in environments with multiple primary sites. We will walk through the process of editing the Microsoft.BDD.CM12Actions.mof file and recompiling it, while also troubleshooting common errors related to the configuration.

Understanding the Issue

MDT task sequences rely on SCCM to deploy operating systems. When there are multiple primary site servers in an SCCM environment, MDT needs to be properly configured to communicate with the correct management point. The Microsoft.BDD.CM12Actions.mof file plays a critical role in defining the SCCM site and management point for MDT to use during deployment.

The problem arises when this file is edited to point to a specific primary site server, but MDT is still unable to perform tasks correctly. This may be due to several reasons such as improper changes to the MOF file, conflicts between multiple primary sites, or issues with the management point that MDT is trying to communicate with.

Step 1: Edit the Microsoft.BDD.CM12Actions.mof File

In environments with multiple primary sites, the Microsoft.BDD.CM12Actions.mof file must be edited carefully to ensure MDT uses the correct site server for its communication. Here's how to do it:

  1. Locate the MOF File
    The Microsoft.BDD.CM12Actions.mof file is located in the AdminConsole\bin folder of your SCCM installation. The path typically looks like this:

<ConfigMgr_Install_Directory>\AdminConsole\bin

Replace <ConfigMgr_Install_Directory> with the actual directory where your SCCM is installed, which by default is:

C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin

  1. Open and Edit the File
    Open the Microsoft.BDD.CM12Actions.mof file using a text editor (e.g., Notepad++). In the file, find the line where the SMS provider or site service is listed. It should look like this:

Provider="sms:<SMSProvider_FQDN>"

  1. Replace the SMS Provider with the Correct Primary Site
    Since there are multiple primary sites in your environment, replace the <SMSProvider_FQDN> with the Fully Qualified Domain Name (FQDN) of the primary site server that you want MDT to use. For example:

Provider="sms:PrimarySiteServer.FQDN"

  1. Save the MOF File
    After making the necessary changes, save the file.

Step 2: Recompile the MOF File

After editing the Microsoft.BDD.CM12Actions.mof file, it must be recompiled to apply the changes. Follow these steps:

  1. Open an Elevated Command Prompt
    Run Command Prompt as an administrator to have the necessary privileges.
  2. Navigate to the Directory
    Use the cd command to navigate to the folder where the Microsoft.BDD.CM12Actions.mof file is located:

cd <ConfigMgr_Install_Directory>\AdminConsole\bin

  1. Compile the MOF File
    Run the following command to recompile the MOF file:

mofcomp Microsoft.BDD.CM12Actions.mof

This command will compile the MOF file and apply the changes to the WMI repository. If successful, you will see a confirmation message.

Conclusion

MDT integration with SCCM is a powerful tool for deploying operating systems, but it can encounter issues when there are multiple primary sites. Editing the Microsoft.BDD.CM12Actions.mof file to update the site service is an essential step in ensuring proper communication. However, if not done carefully, it can lead to issues such as task sequences not being available or MDT failing to communicate with the correct site server.

By following the steps outlined in this blog and troubleshooting common errors, you can ensure a smooth integration of MDT with SCCM, even in environments with multiple primary sites. Always test your changes thoroughly and check the relevant logs to diagnose and resolve any issues.

Troubleshooting and Installing SCCM Clients with PKI Certificates

 

Introduction:

In this blog post, we will go through several important steps to help with SCCM (System Center Configuration Manager) client management, including clearing old configurations, removing certificates, and installing the SCCM client using PKI certificates. We will also cover starting and stopping services, handling the Windows firewall, and ensuring a proper configuration when working with SCCM clients.

Step 1: Stop the SCCM Client Service (ccmexec)

The first step in the cleanup process is to stop the ccmexec service, which is the core service for the SCCM client. This will prevent the client from attempting to run while we perform our cleanup operations.

To stop the ccmexec service, run the following command in an elevated Command Prompt:

net stop ccmexec

This will stop the service temporarily and ensure no background operations are running while you perform the necessary cleanup steps.

Step 2: Delete the SMSCFG.INI File

The SMSCFG.INI file holds important configuration information for the SCCM client. Deleting this file can help resolve issues where the client is incorrectly configured or when you want to reset the client’s configuration to its default state.

Run the following command to delete the file:

del c:\Windows\SMSCFG.INI

This will remove the configuration file. It will be re-generated the next time the SCCM client is initialized.

Step 3: Remove the SCCM Certificate from the SMS Store

In certain cases, you may need to delete the certificate from the SMS certificate store (this could happen when you are troubleshooting issues with certificates or when you want to reset the certificates). To remove the certificate, you can use the certutil command.

Run the following command to delete the certificate from the SMS store:

certutil -delstore SMS SMS

This command deletes the certificate from the SMS store. Be cautious when using this, as it removes the certificate needed for secure communication between the client and the server.

Step 4: Restart the SCCM Client Service (ccmexec)

After performing the cleanup steps, you need to restart the ccmexec service to reinitialize the client. You can do so using the following command:

net start ccmexec

This will start the SCCM client service again, and the client will begin communicating with the SCCM server once more.

Step 5: Start the Windows Firewall Service (if it's stopped)

If the Windows Firewall service is stopped, it can cause communication issues between the SCCM client and the server. To ensure the firewall is running, you can start the service (if it's stopped) by running:

net start mpssvc

This command starts the Windows Firewall service (mpssvc), ensuring that the necessary firewall rules are applied, and the client can communicate over the required ports.

Step 6: Install SCCM Client Using PKI Certificates

If you're setting up the SCCM client and need to configure it to use PKI (Public Key Infrastructure) certificates, you can use the CCMSetup.exe command. This command installs the SCCM client while ensuring that it uses PKI certificates for secure communication with the management point.

Here is the command you will use:

CCMSetup.exe /mp:YOURMP /UsePKICert

  • /mp:YOURMP: Replace YOURMP with the fully qualified domain name (FQDN) of your Management Point (MP). The MP is a key component in the SCCM infrastructure that communicates with the client.
  • /UsePKICert: This flag tells the client to use PKI certificates for secure communication.

When this command is executed, it will install the SCCM client on the machine and ensure that the client communicates securely with the management point using the certificates issued by your PKI infrastructure.

Conclusion

By following these steps, you can troubleshoot SCCM client issues, remove old certificates, reset configurations, and install a new SCCM client using PKI certificates. These operations are crucial for maintaining a healthy SCCM infrastructure and ensuring secure communication between clients and servers.

Wednesday, 27 November 2024

SCCM SQL Query Online device by Management Point

 SCCM SQL Query Online device by Management Point


select srl.SiteCode, srl.ServerName, srl.InternetEnabled, srl.Shared, srl.SslState,

SUM(brs.OnlineStatus) AS OnlineClients, bs.ReportTime from SysResList srl

inner join BGB_Server bs ON srl.ServerName = bs.ServerName

inner join BGB_ResStatus brs ON bs.ServerID = brs.ServerID

where RoleName='SMS Management Point'

group by srl.SiteCode, srl.ServerName, srl.InternetEnabled, srl.Shared, srl.SslState, bs.ReportTime


 SCCM SQL Query Client device count by Management Point


Select Substring(br.AccessMP,1,(PATINDEX('%.%',br.AccessMP)-1)) as Management_Point, 

Count(Substring(br.AccessMP,1,(PATINDEX('%.%',br.AccessMP)-1))) as Total_Clients

from

v_R_System sd join BGB_ResStatus br on sd.ResourceID=br.ResourceID 

Where PATINDEX('%.%',br.AccessMP) > 0

Group By Substring(br.AccessMP,1,(PATINDEX('%.%',br.AccessMP)-1))

Order By Count(Substring(br.AccessMP,1,(PATINDEX('%.%',br.AccessMP)-1))) Desc



Thursday, 24 October 2024

SCCM Configuration Baseline to Initiate Available Task Sequence

 PowerShell Script Monitor

Function Get-RegistryValue12 {

        param (

            [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Path,

            [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Name

        )

        Return (Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name

    }

$compliance = "Compliant"

$Registry = "HKLM:\SOFTWARE\SOFTWARE\WOW6432Node\Notepad++"

$name = "InstallerLanguage"

$value = Get-RegistryValue12 -path $registry -name $name

$Ver = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").currentBuild

If ($Ver -like '1033')

{

$compliance = 'Non-Compliant'

}

$compliance


PowerShell Script Remediation

Function Execute-TaskSequence {

    Param (

        [parameter(Mandatory = $true)]

        [string]$Name

    )

    Try {

        Write-Host "Connecting to the SCCM client Software Center..."

        $softwareCenter = New-Object -ComObject "UIResource.UIResourceMgr"

    }

    Catch {

        Throw "Could not connect to the client Software Center."

    }

    If ($softwareCenter) {

        Write-Host "Searching for deployments for task sequence [$name]..."

        $taskSequence = $softwareCenter.GetAvailableApplications() | Where-Object { $_.PackageName -eq "$Name" }

        If ($taskSequence) {

            $taskSequenceProgramID = $taskSequence.ID

            $taskSequencePackageID = $taskSequence.PackageID

            Write-Host "Found task sequence [$name] with package ID [$taskSequencePackageID]."

            # Execute the task sequence

            Try {

                Write-Host "Executing task sequence [$name]..."

                $softwareCenter.ExecuteProgram($taskSequenceProgramID,$taskSequencePackageID,$true)

                Write-Host "Task Sequence executed."

            }

            Catch {

                Throw "Failed to execute the task sequence [$name]"

            }

        }

        Else {

            Write-Host "No Deployments found matching name = [$name]!"

            exit 100

        }

    }

}

Execute-TaskSequence -name "Custom Task Sequence"

Tuesday, 22 October 2024

SCCM Collection Optimization using PowerShell Script

 SQL Query to Get the current collection evaluation schedule


Select

CG.CollectionName,

CG.SITEID AS [Collection ID],

CASE VC.CollectionType

WHEN 0 THEN ‘Other’

WHEN 1 THEN ‘User’

WHEN 2 THEN ‘Device’

ELSE ‘Unknown’ END AS CollectionType,

CG.schedule, case

WHEN CG.Schedule like ‘%000102000’ THEN ‘Every 1 minute’

WHEN CG.Schedule like ‘%00010A000’ THEN ‘Every 5 mins’

WHEN CG.Schedule like ‘%000114000’ THEN ‘Every 10 mins’

WHEN CG.Schedule like ‘%00011E000’ THEN ‘Every 15 mins’

WHEN CG.Schedule like ‘%000128000’ THEN ‘Every 20 mins’

WHEN CG.Schedule like ‘%000132000’ THEN ‘Every 25 mins’

WHEN CG.Schedule like ‘%00013C000’ THEN ‘Every 30 mins’

WHEN CG.Schedule like ‘%000150000’ THEN ‘Every 40 mins’

WHEN CG.Schedule like ‘%00015A000’ THEN ‘Every 45 mins’

WHEN CG.Schedule like ‘%000100100’ THEN ‘Every 1 hour’

WHEN CG.Schedule like ‘%000100200’ THEN ‘Every 2 hours’

WHEN CG.Schedule like ‘%000100300’ THEN ‘Every 3 hours’

WHEN CG.Schedule like ‘%000100400’ THEN ‘Every 4 hours’

WHEN CG.Schedule like ‘%000100500’ THEN ‘Every 5 hours’

WHEN CG.Schedule like ‘%000100600’ THEN ‘Every 6 hours’

WHEN CG.Schedule like ‘%000100700’ THEN ‘Every 7 hours’

WHEN CG.Schedule like ‘%000100B00’ THEN ‘Every 11 Hours’

WHEN CG.Schedule like ‘%000100C00’ THEN ‘Every 12 Hours’

WHEN CG.Schedule like ‘%000101000’ THEN ‘Every 16 Hours’

WHEN CG.Schedule like ‘%000100008’ THEN ‘Every 1 days’

WHEN CG.Schedule like ‘%000100010’ THEN ‘Every 2 days’

WHEN CG.Schedule like ‘%000100028’ THEN ‘Every 5 days’

WHEN CG.Schedule like ‘%000100038’ THEN ‘Every 7 Days’

WHEN CG.Schedule like ‘%000192000’ THEN ‘1 week’

WHEN CG.Schedule like ‘%000080000’ THEN ‘Update Once’

WHEN CG.SChedule = ” THEN ‘Manual’

END AS [Update Schedule],

Case VC.RefreshType

when 1 then ‘Manual’

when 2 then ‘Scheduled’

when 4 then ‘Incremental’

when 6 then ‘Scheduled and Incremental’

else ‘Unknown’

end as RefreshType,

VC.MemberCount

from

dbo.collections_g CG

left join v_collections VC on VC.SiteID = CG.SiteID

order by

CG.Schedule DESC


Powershell Script to update the evaluation schedule


# site code.

$sitecode = '123'


# name of server hosting the sms provider.

$provider = 'ServerName'


# create a recuring interval token with a cycle of x days.

# the start time will be randomised, but always on the hour.

function new-token($days = 1) {

  $class = gwmi -list -name root\sms\site_$sitecode -class sms_st_recurinterval -comp $provider

  $interval = $class.createinstance()

  $interval.dayspan = $days

  $interval.starttime = get-date (get-date '1/1/2016').addhours((get-random -max 24)) -format yyyyMMddHHmmss.000000+***

  return $interval

}


# get the names of all collections enabled for incremental updates.

function get-incremental() {

  $collections = @()

  gwmi -name root\sms\site_$sitecode -class sms_collection -comp $provider | %{

    $collection = [wmi]$_.__path

    if ($collection.refreshtype -band 4 -and $collection.collectionid -notlike 'sms*') {

      $collections += $collection.name

    }

  }

  return $collections

}


# configure the refresh cycle for an array of collections.

# set $type to 2 for periodic refresh only, and 6 for incremental and periodic.

# set $days to the number days between each periodic refresh.

function set-schedule([array]$collections, $type, $days) {

  $collections | %{

    if (! ($collection = gwmi -name root\sms\site_$sitecode -class sms_collection -comp $provider -filter "name = '$_'")) { return }

    $collection.refreshtype = $type

    $collection.refreshschedule = new-token $days

    #$collection.psbase()

    $collection.put() | out-null

  }

}


# disable incremental updates.

# i.e. enable periodic updates only, with a refresh cycle of 1 day.

function disable-incremental([array]$collections) {

  set-schedule $collections 2 7

}


# enable incremental updates.

# i.e. enable incremental and periodic updates, with a refresh cycle of 7 days.

function enable-incremental([array]$collections) {

  set-schedule $collections 6 7

}

#To retrieve the name of all collections enabled for incremental updates:


#get-incremental

#To disable incremental updates on all collections listed in a file named disable.txt, and enable periodic updates with a daily cycle:


disable-incremental (get-content "C:\Temp\Collection.txt")

#To enable incremental and periodic updates on all collections listed in a file named disable.txt, with a weekly periodic refresh cycle:


#enable-incremental (get-content enable.txt)

Thursday, 3 October 2024

Intune Blocking Store App and allow them updated

 Below configuration profile will help to block the store app 

Administrative Templates\Windows Components\Store

Turn off the Store application (User) and set Enabled


Administrative Templates\Start Menu and Taskbar

Do not allow pinning Store app to the Taskbar (User) and set Enabled


Regardless of how you are blocking or allowing the Microsoft Store, remembering that the store needs to be available to allow for apps from Microsoft Intune to be deployed, we should at least configure devices to allow for updates


Administrative Templates\Windows Components\Store

Allow apps from Microsoft app store to auto update


You can also use the remediation script to allow store app auto update


Detection Script


$Path = "HKLM:\SOFTWARE\Policies\Microsoft\WindowsStore"

$Name = "AutoDownloaded"

$Value = 4


Try {

    $Registry = Get-ItemProperty -Path $Path -Name $Name -ErrorAction Stop | Select-Object -ExpandProperty $Name

    If ($Registry -eq $Value){

        Write-Output "Compliant"

        Exit 0

    } 

    Write-Warning "Not Compliant"

    Exit 1

Catch {

    Write-Warning "Not Compliant"

    Exit 1

}


Remediation Script


Write-Host "Required Auto Update"

$store = "HKLM:\SOFTWARE\Policies\Microsoft\WindowsStore"

If (!(Test-Path $store)) {

    New-Item $store

}

Set-ItemProperty $store AutoDownloaded -Value 4


Tuesday, 24 September 2024

SCCM Configuration Item to Start, Stop, Refresh and Restart Services on client devices

In this post, we will be discussing the topic of how to Enable or Disable Services and how to Start, Stop, Refresh and Restart Services on client device

---Monitor Script

# Define the service name

$serviceName = "PFERemediation"

# Confirm the service status

$service = Get-Service -Name $serviceName

 # Check if the service is stopped and disabled

if ($service.Status -eq 'Stopped' -and $service.StartType -eq 'Disabled') {

    Write-Output "compliance"

} else {

    Write-Output "non-compliance"

}

--Remediation Script

# Define the service name

$serviceName = "PFERemediation"

 # Stop the service

Stop-Service -Name $serviceName -Force

# Disable the service

Set-Service -Name $serviceName -StartupType Disabled

 # Confirm the service status

$service = Get-Service -Name $serviceName

# Check if the service is stopped and disabled

if ($service.Status -eq 'Stopped' -and $service.StartType -eq 'Disabled') {

    Write-Output "compliance"

} else {

    Write-Output "non-compliance"

}

More command line 

Automatic (Delayed Start))​

Set-Service -Name "ServiceName" -StartupType AutomaticDelayedStart​

OR​

(Automatic)​

Set-Service -Name "ServiceName" -StartupType Automatic​

OR​

(Manual)​

Set-Service -Name "ServiceName" -StartupType Manual​

(Automatic (Delayed Start))​

Set-Service -Name "ServiceName" -StartupType AutomaticDelayedStart -Status Running​

OR​

(Automatic)​

Set-Service -Name "ServiceName" -StartupType Automatic -Status Running​

OR​

(Manual)​

Set-Service -Name "ServiceName" -StartupType Manual -Status Running

Set-Service -Name "ServiceName" -StartupType Disabled -Status Stopped

Thursday, 19 September 2024

SCCM WMI Repair using powershell script

 Script 1:

cls

Cd C:\temp\PSTools

$computers = Get-Content "C:\Temp\repairWMI\Input.txt"


Foreach ($computer in $computers)

{

 $filecopy = "\\"+$computer+"\C$"

 $comp = "\\"+$computer

 if (Test-Path $filecopy)

  {

  Copy-Item "C:\Temp\repairWMI\TorepairWMI.ps1" -Destination $filecopy -Force

  Start-sleep 5 

  .\PsExec.exe -i -s $comp PowerShell.exe -noninteractive -File "C:\TorepairWMI.ps1"

   

  }


}

 Script 2:

Function Repair-WMI {

        

        CD C:\Windows\System32\WBEM

        cmd /C "dir /b *.mof *.mfl | findstr /v /i uninstall > moflist.txt & for /F %s in (moflist.txt) do mofcomp %s"

       

        CD "C:\Program Files\Microsoft Policy Platform"

        cmd /C "mofcomp ExtendedStatus.mof"

        # Check PATH

                # Stop WMI

        Stop-Service -Force ccmexec -ErrorAction SilentlyContinue

        Stop-Service -Force winmgmt


        # WMI Binaries

        [String[]]$aWMIBinaries=@("unsecapp.exe","wmiadap.exe","wmiapsrv.exe","wmiprvse.exe","scrcons.exe")

        foreach ($sWMIPath in @(($ENV:SystemRoot+"\System32\wbem"),($ENV:SystemRoot+"\SysWOW64\wbem"))) {

            if(Test-Path -Path $sWMIPath){

                push-Location $sWMIPath

                foreach($sBin in $aWMIBinaries){

                    if(Test-Path -Path $sBin){

                        $oCurrentBin=Get-Item -Path  $sBin

                        & $oCurrentBin.FullName /RegServer

                    }

                    else{

                        # Warning only for System32

                        if($sWMIPath -eq $ENV:SystemRoot+"\System32\wbem"){

                            Write-Warning "File $sBin not found!"

                        }

                    }

                }

               

            }

        }

}

Repair-WMI

Start-sleep 10

Remove-Item C:\TorepairWMI.PS1 -Force

Tuesday, 30 July 2024

PowerShell Script - SCCM Remove In progress packages from all Distribution Points

 function ExecuteSqlQuery ($Server, $Database, $SQLQuery) { 

     $Datatable = New-Object System.Data.DataTable 

      

     $Connection = New-Object System.Data.SQLClient.SQLConnection 

     $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;" 

     $Connection.Open() 

     $Command = New-Object System.Data.SQLClient.SQLCommand 

     $Command.Connection = $Connection 

     $Command.CommandText = $SQLQuery 

     $Reader = $Command.ExecuteReader() 

     $Datatable.Load($Reader) 

     $Connection.Close() 

      

     return $Datatable 

 }


Cls



$packagetoremove  = Get-Content -LiteralPath "D:\Script-New\ToremovePackagesFromInProgressDPs\Input.txt"


$count = $report.count


$series = 1



Foreach ($p in $packagetoremove)

{


 [string] $Server= "Servername" 

 [string] $Database = "CM_123" 

 [string] $UserSqlQuery= $("SELECT vSMS_DPStatusDetails.PackageID,v_Package.Name ,vSMS_DPStatusDetails.DPName,CASE

WHEN vSMS_DPStatusDetails.MessageState = 1 THEN 'Success'WHEN vSMS_DPStatusDetails.MessageState = 2 THEN 'InProgress'WHEN vSMS_DPStatusDetails.MessageState = 4 THEN 'Failed'END AS [State]

FROM            vSMS_DPStatusDetails INNER JOIN

                         v_Package ON vSMS_DPStatusDetails.PackageID = v_Package.PackageID

WHERE vSMS_DPStatusDetails.PackageID = 'CM0004DF' and vSMS_DPStatusDetails.MessageState != '1'

GROUP BY vSMS_DPStatusDetails.DPName, vSMS_DPStatusDetails.MessageState,vSMS_DPStatusDetails.PackageID,v_Package.Name

ORDER BY State") 


  # declaration not necessary, but good practice  

  $Report = New-Object System.Data.DataTable 

 $Report = ExecuteSqlQuery $Server $Database $UserSqlQuery


 Foreach ($app in $report)

 {

  $pkgid = $app.PackageID

  $dp = $app.DPName

  $appname = $app.Name

   Write-Host "Removing "  $appname" from "  $dp ------- $series " From total of " $count


 

  Remove-CMContentDistribution -ApplicationName '$appname'  -DistributionPointName $dp -Force


  $app = " "

  

  $series++ 

   

 }


 $p = " "


 $report = " " 

 }


Wednesday, 13 March 2024

SCCM SQL Query to get Bit-locker Recovery Key

 

SELECT

cm.Name,

ck.RecoveryKeyId,

cv.VolumeGuid,

cvt.TypeName AS 'Volume Type',

RecoveryAndHardwareCore.DecryptString(ck.RecoveryKey, DEFAULT) AS RecoveryKey,

RecoveryAndHardwareCore.DecryptBinary(ck.RecoveryKeyPackage, DEFAULT) AS BitLockerRecoveryKeyPackage,

ck.LastUpdateTime

FROM RecoveryAndHardwareCore_Keys ck

INNER JOIN RecoveryAndHardwareCore_Volumes cv on ck.VolumeID = cv.ID

LEFT JOIN RecoveryAndHardwareCore_VolumeTypes cvt on cv.VolumeTypeId = cvt.Id

LEFT JOIN RecoveryAndHardwareCore_Machines_Volumes cmv on cv.Id = cmv.VolumeId

LEFT JOIN RecoveryAndHardwareCore_Machines cm on cmv.MachineId = cm.Id

Friday, 16 February 2024

SCCM SQL Query for Windows Build Version and Support State

 select 

VRS.name0 as [Computer Name],

OS.Caption0 as [Operating System],

VRS.User_Name0 , 

WSLN.Value as [Windows 10 build Version],

Case WSLN.Value

WHEN 'Windows 10 2015 LTSB' THEN 'Windows 10, version 2015'

WHEN 'Windows 10 2016 LTSB' THEN 'Windows 10, version 2016'

ELSE WSLN.Value

END as Value,

CASE WSS.Branch  

         WHEN '0' THEN 'Current Branch'  

         WHEN '1' THEN 'Current Branch for Business'  

         WHEN '2' THEN 'Long Term Servicing Branch'  

END as 'Branch',  

CASE WSS.State 

WHEN '1' THEN 'Release Ready'  

WHEN '2' THEN 'Supported'  

WHEN '3' THEN 'Expires Soon'  

WHEN '4' THEN 'End of Life'   

END as 'State',

CHS.ClientStateDescription , 

CHS.LastActiveTime

from v_R_System VRS

JOIN vSMS_WindowsServicingStates WSS on VRS.OSBranch01 = WSS.Branch and VRS.Build01 = WSS.Build

JOIN vSMS_WindowsServicingLocalizedNames WSLN on WSS.Name = WSLN.Name

join v_GS_OPERATING_SYSTEM OS on VRS.ResourceID = OS.ResourceID

join v_CH_ClientSummary CHS on VRS.ResourceID = CHS.ResourceID

Friday, 9 February 2024

PowerShell Script to add Operating System Install Date in Registry

 $Date = Get-date 

$Registry = "Registry::HKLM\SOFTWARE\CompanyName"

$Registry1 = "Registry::HKLM\SOFTWARE\CompanyName\OperatingSystem"

$name = "OperatingSystem"

if (!(Test-Path -Path $Registry))

 {

  

  New-Item -Path $Registry -Force | Out-Null

  New-Item -Path $Registry1 -Force | Out-Null

  New-ItemProperty -LiteralPath $Registry1 -Name $name -Value $Date -PropertyType 'String' -Force | Out-Null

 }

Elseif (!(Test-path -Path $Registry1))

 {

   New-Item -Path $Registry1 -Force | Out-Null

  New-ItemProperty -LiteralPath $Registry1 -Name $name -Value $Date -PropertyType 'String' -Force | Out-Null

 }

 Else

 {

 New-ItemProperty -LiteralPath $Registry1 -Name $name -Value $Date -PropertyType 'String' -Force | Out-Null

 }


Tuesday, 16 January 2024

SCCM Powershell Script to Force Hardware Inventory using Script Option

 $LogFile = "$ENV:TEMP\HwInventRepair.log"

# Invoke a full (resync) HWI report

$Instance = Get-CimInstance -NameSpace ROOT\ccm\InvAgt -Query "SELECT * FROM InventoryActionStatus WHERE InventoryActionID='{00000000-0000-0000-0000-000000000001}'"

Set-Content -Path $LogFile -Value $Instance

$Instance | Remove-CimInstance

Add-Content -Path $LogFile -Value "Instance removed."

Invoke-CimMethod -Namespace ROOT\ccm -ClassName SMS_Client -MethodName TriggerSchedule -Arguments @{ sScheduleID = "{00000000-0000-0000-0000-000000000001}"}

Add-Content -Path $LogFile -Value "Trigger Hardware Inventory"

Start-Sleep -Seconds 5

 # Check InventoryAgent log for ignored message

$Log = "$env:SystemRoot\CCM\Logs\InventoryAgent.Log"

$LogEntries = Select-String –Path $Log –SimpleMatch "{00000000-0000-0000-0000-000000000001}" | Select -Last 1

If ($LogEntries -match "already in queue. Message ignored.")

{

    # Clear the message queue

    # WARNING: This restarts the SMS Agent host service

    Add-Content -Path $LogFile -Value "Hardware Inventory already triggered, may be hung."

    Stop-Service -Name CcmExec -Force

    Add-Content -Path $LogFile -Value "CcmExec service stopped."

    Remove-Item -Path C:\Windows\CCM\ServiceData\Messaging\EndpointQueues\InventoryAgent -Recurse -Force -Confirm:$false

    Add-Content -Path $LogFile -Value "Inventory Agent files deleted."

    Start-Service -Name CcmExec

    Add-Content -Path $LogFile -Value "CcmExec service started."

    # Invoke a full (resync) HWI report

    Start-Sleep -Seconds 5

    $Instance = Get-CimInstance -NameSpace ROOT\ccm\InvAgt -Query "SELECT * FROM InventoryActionStatus WHERE InventoryActionID='{00000000-0000-0000-0000-000000000001}'"

    Add-Content -Path $LogFile -Value $Instance

    $Instance | Remove-CimInstance

    Add-Content -Path $LogFile -Value "Instance removed again."

    Invoke-CimMethod -Namespace ROOT\ccm -ClassName SMS_Client -MethodName TriggerSchedule -Arguments @{ sScheduleID = "{00000000-0000-0000-0000-000000000001}"}

    Add-Content -Path $LogFile -Value "Trigger Hardware Inventory"

Friday, 12 January 2024

SCCM PowerShell Script to Remediate Windows Auto Update / Upgrade Issue

 Monitor 

$RegistryPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'

$RegistryPath1 = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'

$RegistryPath2 = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate'

$Name = 'NoAutoUpdate'

$Name1 = 'AUOptions'

$Name2 = 'DisableDualScan'

$value = $(Get-ItemProperty $RegistryPath -Name $Name -ErrorAction SilentlyContinue ).$Name

$value1 = $(Get-ItemProperty $RegistryPath1 -Name $Name1 -ErrorAction SilentlyContinue ).$Name1

$value2 = $(Get-ItemProperty $RegistryPath2 -Name $Name2 -ErrorAction SilentlyContinue ).$Name2

If ($value -eq 0 -or $value1 -eq 'AUOptions' -or $value2 -eq 0)

{Write-Host "Non-Compliant"}

Else

{Write-Host "Compliant"}


Remediation


$RegistryPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'

$RegistryPath1 = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'

$RegistryPath2 = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\'

$Name = 'NoAutoUpdate'

$Name1 = 'AUOptions'

$Name2 = 'DisableDualScan'

$value = $(Get-ItemProperty $RegistryPath -Name $Name -ErrorAction SilentlyContinue ).$Name

$value1 = $(Get-ItemProperty $RegistryPath1 -Name $Name1 -ErrorAction SilentlyContinue ).$Name1

$value2 = $(Get-ItemProperty $RegistryPath2 -Name $Name2 -ErrorAction SilentlyContinue ).$Name2

If ($value -eq 0)

{

New-ItemProperty -Force -Path $RegistryPath -Name $Name -Value '1' -PropertyType "DWord"

}

If ($value1 -ne 'AUOptions')

{

Remove-ItemProperty -Path $RegistryPath1 -Name $Name1 -Force -Confirm:$false

}

If ($value2 -eq 0)

{

New-ItemProperty -Force -Path $RegistryPath2 -Name $Name2 -Value '1' -PropertyType "DWord"

}

Thursday, 11 January 2024

Intune PowerShell script to remediate Windows device sync issue

 Monitor Script

$DmWapPushSvcState = Get-ItemPropertyValue -Path "HKLM:\SYSTEM\CurrentControlSet\Services\dmwappushservice" -Name "Start"

 if ($DmWapPushSvcState -eq '2')

{

    Write-Output "DmWapPushSvc is in Enabled state"        

    exit 0

}

else

{

    Write-Output "DmWapPushSvc is in Disabled state"

    exit 1

}

Remediation Script

Invoke-Command {reg import "C:\ProgramData\DmWapPushService\dmwappushsvc.reg" *>&1 | Out-Null}

 $DmWapPushSvcState = Get-ItemPropertyValue -Path "HKLM:\SYSTEM\CurrentControlSet\Services\dmwappushservice" -Name "Start"

 if ($DmWapPushSvcState -eq '2') 

{

        exit 0

else

{

        Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\dmwappushservice" -Name "Start" -Value '2'

        exit 1

}

Powershell script to check HTTPS MP Health Status

This is because the SCCM client uses a computer certificate to communicate with the management point, but when you are using a normal user you don’t have access to this certificate.

We can specify a certificate to use by using PowerShell as an admin and running the command Invoke-WebRequest.

PowerShell

Copy

$cert = Get-ChildItem -Path "cert:\LocalMachine\My\<ThumbprintOfCert>"

Invoke-WebRequest -Uri "https://<mp_server_name>/sms_mp/.sms_aut?mplist" -Certificate $cert

 }

PowerShell Script for Intune Proactive Remediation (Google Chrome)

 Monitor Script

try

{  

$chromeInstalled = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'

if ($chromeInstalled -eq 'True') {

    Write-Host "Google Chrome is installed"

    exit 1

    }

    else {

        #No remediation required    

        Write-Host "Google Chrome is not installed"

        exit 0

    }  

}

catch {

    $errMsg = $_.Exception.Message

    Write-Error $errMsg

    exit 1

}

Remediate Script

# Start-Process Installers and Arguments

$Installer = "$env:ProgramFiles\Google\Chrome\Application\$ChromeVersion\Installer\chrmstp.exe"

$InstallerX86 = "${env:ProgramFiles(x86)}\Google\Chrome\Application\$ChromeVersion\Installer\chrmstp.exe"

$Arguements = "--uninstall --chrome --system-level --multi-install --force-uninstall"


$chromeInstalled = (Get-Item (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe' -ErrorAction SilentlyContinue).'(Default)').VersionInfo

 $ChromeVersion = $chromeInstalled.ProductVersion


 # Check for x64 Chrome

 $Chromex64 = "C:\Program Files\Google\Chrome\Application\$ChromeVersion\Installer\chrmstp.exe"

 $FileExistsx64 = Test-Path $Chromex64


 # Check for x86 Chrome

 $Chromex86 = "C:\Program Files (x86)\Google\Chrome\Application\$ChromeVersion\Installer\chrmstp.exe"

 $FileExistsx86 = Test-Path $Chromex86


 # Remove x64 Chrome

 If ($FileExistsx64 -eq $True) {

    Start-Process $Installer $Arguements -Wait

 }

  

  # Remove x86 Chrome

 If ($FileExistsx86 -eq $True) {

    Start-Process $InstallerX86 $Arguements -Wait

Friday, 5 January 2024

SCCM Close application using PowerShell - Popup

Powershell Script

 # add the required .NET assembly:

Add-Type -AssemblyName System.Windows.Forms

# show the MsgBox:

$result = [System.Windows.Forms.MessageBox]::Show('Please Click "Yes"  to close Google Chrome, click No to dont close  ', 'Info', 'YesNo', 'Warning')

# check the result:

if ($result -eq 'Yes')

{

  # Call the SSMS app with silent/no restart switch with exit code  

  #.\SSMS-Setup-ENU.exe /install /quiet /norestart     actuall isntallation from CMD

  (Stop-Process -Name "chrome" )

  Write-Warning 'Chrome Closed'

}

else

{

  Write-Warning 'Chrome Still Open'

}

Application Deployment Type – Program

Powershell.exe -ExecutionPolicy ByPass -File Your-Scriptfilename.PS1

Package – Program CMD Line

"%Windir%\sysnative\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -Command .\Your-Scriptfilename.ps1

PSAppDeployToolkit in Intune to Check Interactive Session and Install Application with Notifications

  How to Use PSAppDeployToolkit  in Intune to Check Interactive Session and Install Google Chrome with Notifications Managing software insta...