troubleshooting Question

Powershell, condition help - taking action only if criteria met

Avatar of Ron Shorts
Ron ShortsFlag for United States of America asked on
PowershellHTMLScripting Languages
1 Comment1 Solution79 ViewsLast Modified:
Hi Experts,

I have two script below, one is a wrapper script calling or passing arguments to the other.

I'm looking to have this only send the email or take action if the criteria is met that I have in the command line arguments ( Get-CMClientExecutionHistory-Worker -Computername $Computer | Where-Object SuccessOrFailureCode -ne 0 ) for the computers in the list.

Right now this sends to every computer in the list I have, if the command line criteria isn't met, it's blank output.

I'm stuck on how to go about setting this up, any help is appreciated.

# Get-CimClientExecutionHistory-Worker.ps1
    [string[]]$ComputerName = $env:COMPUTERNAME


$Code = {
    # Get Execution History from registry, and package details from WMI
    $ExecutionHistoryKey = "HKLM:\SOFTWARE\Microsoft\SMS\Mobile Client\Software Distribution\Execution History" 
    $ContextKeys = Get-ChildItem $ExecutionHistoryKey | Select -ExpandProperty PSChildName
    foreach ($ContextKey in $ContextKeys)
        If ($ContextKey -eq "System")
            $ContextKey = "Machine"
            $ContextKey = $ContextKey.Replace('-','_')
        [array]$SoftwareDistribution += Get-CimInstance -Namespace ROOT\ccm\Policy\$ContextKey -ClassName CCM_SoftwareDistribution

    # Create a datatable to hold the results
    $DataTable = New-Object System.Data.DataTable

    foreach ($ContextKey in $ContextKeys)
        If ($ContextKey -ne "System")
            # Get user context if applicable
            $SID = New-Object Security.Principal.SecurityIdentifier -ArgumentList $ContextKey
            $Context = $SID.Translate([System.Security.Principal.NTAccount])
            $Context = "Machine"
        $SubKeys = Get-ChildItem "$ExecutionHistoryKey\$ContextKey" 
        Foreach ($SubKey in $SubKeys)
            $Items = Get-ChildItem $SubKey.PSPath
            Foreach ($Item in $Items)
                $PackageInfo = $SoftwareDistribution | Where {$_.PKG_PackageID -eq $SubKey.PSChildName -and $_.PRG_ProgramName -eq $Item.GetValue("_ProgramID")} | Select -First 1
                If ($PackageInfo)
                    $PackageName = $PackageInfo.PKG_Name
                    $DeploymentStatus = "Active"
                    $PackageName = "-Unknown-"
                    $DeploymentStatus = "No longer targeted"

    $DataTable.DefaultView.Sort = "RunStartTime DESC"
    $DataTable = $DataTable.DefaultView.ToTable()
    Return $DataTable


foreach ($Computer in $ComputerName)
    If ($Computer -eq $env:COMPUTERNAME)
        $Result = Invoke-Command -ScriptBlock $Code
        $Result = Invoke-Command -ComputerName $Computer -HideComputerName -ScriptBlock $Code -ErrorAction Continue
    $Result | Select ComputerName,PackageName,PackageID,ProgramName,DeploymentStatus,Context,State,RunStartTime,SuccessOrFailureCode,SuccessOrFailureReason 


# Get-CimClientExecutionHistory-Wrapper.ps1
$ComputerList  = Get-Content "C:\Get-CMClientExecutionHistoryInput\computerlist001.txt"
$Outfile = "C:\Get-CMClientExecutionHistoryInput\ExecutionHistory.csv"

# param([string[]]$computers)
foreach ($computer in $computerlist) {

# with -ne 0 filter
$Results = .\Get-CMClientExecutionHistory-Worker -Computername $Computer | Where-Object SuccessOrFailureCode -ne 0 | Select-Object Computername, State, PackageName, SuccessOrFailureCode, SuccessOrFailureReaseon, PackageID, ProgramName, DeploymentStatus, RunStartTime

If ($results) {
	$results | Export-Csv -NoTypeInformation -Append -Path $outFile

$SmtpServer = ""
$SmtpFrom = ""
$SmtpTo =  "admin@relay"

$SmtpSubject = "Advertisement Failure on $computername"

$reporthtml = $results | ConvertTo-Html -fragment

				BODY{font-family: sans-serif; font-size: 9pt;}
				H1{font-size: 18px; font-family: ""Trebuchet MS"", Arial, Helvetica, sans-serif;}
				H2{font-size: 18px; font-family: ""Trebuchet MS"", Arial, Helvetica, sans-serif;}
				H3{font-size: 16px; font-family: ""Trebuchet MS"", Arial, Helvetica, sans-serif;}
				H4{font-size: 12px; font-family: ""Trebuchet MS"", Arial, Helvetica, sans-serif;}
				TABLE{border: 1px solid black; border-collapse: collapse; font-size: 9pt;}
				TH{border: 1px solid #969595; background: #1FE093; padding: 5px; color: #000000;}
				TD{border: 1px solid #969595; padding: 5px; }
				td.pass{background: #B7EB83;}
				td.warn{background: #FFF275;}{background: #1FE093; color: #ffffff;}{background: #1FE093;}
                <h1 align=""Left"">Advertisement failure</h1>"

  $htmltail = "</body> <br>

Advertisements failure code.<br><br>"

 $htmlreport = $htmlhead + $reporthtml + $htmltail 

 Send-MailMessage -From $SmtpFrom -To $SmtpTo -Subject $SmtpSubject -SmtpServer $SmtpServer -bodyashtml -Body $htmlreport  

Ron Shorts

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros