Link to home
Start Free TrialLog in
Avatar of Ron Shorts
Ron ShortsFlag for United States of America

asked on

Powershell, condition help - taking action only if criteria met

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
[quote][CmdletBinding()]
Param
(
    [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [string[]]$ComputerName = $env:COMPUTERNAME
)

Begin
{

$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"
        }
        Else
        {
            $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
    [void]$DataTable.Columns.Add("ComputerName")
    [void]$DataTable.Columns.Add("PackageName")
    [void]$DataTable.Columns.Add("PackageID")
    [void]$DataTable.Columns.Add("ProgramName")
    [void]$DataTable.Columns.Add("DeploymentStatus")
    [void]$DataTable.Columns.Add("Context")
    [void]$DataTable.Columns.Add("State")
    [void]$DataTable.Columns.Add("RunStartTime")
    [void]$DataTable.Columns.Add("SuccessOrFailureCode")
    [void]$DataTable.Columns.Add("SuccessOrFailureReason")

    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])
        }
        Else
        {
            $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"
                }
                Else
                {
                    $PackageName = "-Unknown-"
                    $DeploymentStatus = "No longer targeted"
                }
                [void]$DataTable.Rows.Add($using:Computer,$PackageName,$SubKey.PSChildName,$Item.GetValue("_ProgramID"),$DeploymentStatus,$Context,$Item.GetValue("_State"),$Item.GetValue("_RunStartTime"),$Item.GetValue("SuccessOrFailureCode"),$Item.GetValue("SuccessOrFailureReason"))
            }
        }
    }

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

}
Process
{

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

}
End
{
}
[/quote]

Open in new window


# 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 = "mail.relay.com"
$SmtpFrom = "admin@relay.com"
$SmtpTo =  "admin@relay"

$SmtpSubject = "Advertisement Failure on $computername"

$reporthtml = $results | ConvertTo-Html -fragment

$htmlhead=$htmlhead="<html>
				<style>
				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;}
				td.fail{background: #1FE093; color: #ffffff;}
				td.info{background: #1FE093;}
				</style>
				<body> 
                <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  



 }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ron Shorts
Ron Shorts
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial