Additional tools

Jul 8, 2013 at 8:19 PM
Edited Jul 8, 2013 at 8:27 PM
First of all, I would like to thank you for all of these scripts...they are quite handy.

I have also written some additional tools which expand on the functionality of your scripts, so I thought I'd share them with you.
  1. Device - Display Running Jobs - Displays applications/programs/updates that are waiting to install or currently installing.
  2. Collection - Safe Reboot - Reboots computers in a collection with no user logged in, if the computer requires a reboot from windows updates. (Great if you aren't forcing reboots)
  3. Collection - ReRun Advertisement - Reruns selected "old style" program on all the computers in the collection.
  4. Device - Install Missing Updates.ps1 - Installs all available software updates. (Same as using Software Center, selecting all available updates and clicking install)
The code for these are quiet long, and not quite as eloquent as the other scripts, so I'll post the code in separate posts.
Jul 8, 2013 at 8:20 PM
Script 1:

Device - Display Running Jobs:
function Expand-String 
{ 
   param( 
       [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] 
       [System.String]$Value, 

       [switch]$EnvironmentVariable 
   )

   if($EnvironmentVariable) { 
      [System.Environment]::ExpandEnvironmentVariables($Value) 
   } 
   else 
   { 
      $ExecutionContext.InvokeCommand.ExpandString($Value) 
   } 
} 

function LoadForm($ComputerName)
{
$table.Clear()
$rform1.refresh()
#[System.Windows.Forms.MessageBox]::Show("Displaying Running Jobs for: $ComputerName" , "Click OK")
    #If you can ping it the device
    If(Test-Connection -Cn $ComputerName -BufferSize 16 -Count 2 -ea 0 -quiet){
            $rError = ""

                    #Get Running Programs from WMI
                    $wmiObject = Get-WmiObject -class CCM_ExecutionRequestex -NameSpace "root\ccm\softmgmtagent" -ComputerName $ComputerName
                    $table.Clear
                    If(!$wmiObject){
                    } else {
                        Foreach($job in $wmiObject){
                            $resultrow = @(($job.AdvertID),($job.ProgramID),($job.State),($job.ContentID),($job.RequestID))
                            $table.Rows.Add($resultrow)
                        }
                    }

                    
                            #Get Running Applications from WMI
            $wmiObject = Get-WmiObject -class CCM_Application -NameSpace "root\ccm\ClientSDK" -ComputerName $ComputerName | where {$_.EvaluationState -gt 5}
            If(!$wmiObject){
            } else {
                Foreach($job in $wmiObject){
                    $Evalstate = $job.EvaluationState
                    Switch ($Evalstate)
                    {
                         5 { $Evalstate = 'Application is currently waiting for content download to complete.' }
                         6 { $Evalstate = 'Application is currently waiting for content download to complete.' }
                         7 { $Evalstate = 'Application is currently waiting for its dependencies to download.' }
                         8 { $Evalstate = 'Application is currently waiting for a service (maintenance) window.' }
                         9 { $Evalstate = 'Application is currently waiting for a previously pending reboot.' }
                         10 { $Evalstate = 'Application is currently waiting for serialized enforcement.' }
                         11 { $Evalstate = 'Application is currently enforcing dependencies.' }
                         12 { $Evalstate = 'Application is currently enforcing.' }
                         13 { $Evalstate = 'Application install/uninstall enforced and soft reboot is pending.' }
                         14 { $Evalstate = 'Application installed/uninstalled and hard reboot is pending' }
                         15 { $Evalstate = 'Update is available but pending installation.' }
                         16 { $Evalstate = 'Application failed to evaluate.' }
                         17 { $Evalstate = 'Application is currently waiting for an active user session to enforce.' }
                         18 { $Evalstate = 'Application is currently waiting for all users to logoff.' }
                         19 { $Evalstate = 'Application is currently waiting for a user logon.' }
                         20 { $Evalstate = 'Application in progress, waiting for retry.' }
                         21 { $Evalstate = 'Application is waiting for presentation mode to be switched off.' }
                         22 { $Evalstate = 'Application is pre-downloading content' }
                         23 { $Evalstate = 'Application is pre-downloading dependent content' }
                         24 { $Evalstate = 'Application download failed' }
                         25 { $Evalstate = 'Application pre-downloading failed' }
                         26 { $Evalstate = 'Download success' }
                         27 { $Evalstate = 'Post-enforce evaluation.' }
                         28 { $Evalstate = 'Waiting for network connectivity.' }
                         Default { 'No Information Available' }
                    }
                    $resultrow = @(($job.Name),($job.FullName),($Evalstate),(""),($job.ID))
                    $table.Rows.Add($resultrow)
                }
            }
            
            #Get Running Software Updates from WMI
            $wmiObject = Get-WmiObject -class CCM_SoftwareUpdate -NameSpace "root\ccm\ClientSDK" -ComputerName $ComputerName  | where {$_.EvaluationState -gt 1}
            If(!$wmiObject){
            } else {
                Foreach($job in $wmiObject){
                    $Evalstate = $job.EvaluationState
                    Switch ($Evalstate)
                    {
                        1 { $Evalstate = 'Update is available' }
                        2 { $Evalstate = 'Update submitted' }
                        3 { $Evalstate = 'Update detecting' }
                        4 { $Evalstate = 'Update starting download' }
                         5 { $Evalstate = 'Update is currently waiting for content download to complete.' }
                         6 { $Evalstate = 'Update is currently waiting for install to start.' }
                         7 { $Evalstate = 'Update is currently waiting for install to complete.' }
                         8 { $Evalstate = 'Update is currently waiting for a soft reboot.' }
                         9 { $Evalstate = 'Update is currently waiting for a hard reboot.' }
                         10 { $Evalstate = 'Update is currently waiting for a reboot.' }
                         11 { $Evalstate = 'Update is currently verifying the installation' }
                         12 { $Evalstate = 'Update install complete.' }
                         13 { $Evalstate = 'Update install failed.' }
                         14 { $Evalstate = 'Update is waiting for an available maintenance window' }
                         15 { $Evalstate = 'Update is waiting for user logon.' }
                         16 { $Evalstate = 'Update is waiting for user log off' }
                         17 { $Evalstate = 'Update is waiting for user logon' }
                         18 { $Evalstate = 'Update is waiting for user to reconnect.' }
                         19 { $Evalstate = 'Update is waiting for user log off' }
                         20 { $Evalstate = 'Update pending' }
                         21 { $Evalstate = 'Update is waiting for retry' }
                         Default { 'Update in unknown state' }
                    }
                    $resultrow = @(($job.Name),($job.FullName),($Evalstate),(""),($job.UpdateID))
                    $table.Rows.Add($resultrow)
                }
            }
            
        
                

    }else{
        $rError = "Failed to Ping Device"
        [System.Windows.Forms.MessageBox]::Show($rError , "ERROR")
        $ProcessID = [System.Diagnostics.Process]::GetCurrentProcess()
        $ProcID = $ProcessID.ID
        & taskkill /PID $ProcID /T /F
        Break
    }
                $rDataGrid1.DataSource = $table

                $rform1.Controls.Add($rDataGrid1)
                $rform1.Controls.Add($button1)
                $rform1.Controls.Add($label1)
                $time = get-date -format hh:mm:ss
                $label1.Text = "Last Refresh: $time"
                $rform1.refresh()
}

$ComputerName = $args[0] 
# [System.Windows.Forms.MessageBox]::Show("Displaying Running Jobs for: $ComputerName" , "Click OK")

If (!($ComputerName)) {
    [System.Windows.Forms.MessageBox]::Show("Invalid Device" , "ERROR")
    Break
}
If(!(Test-Connection -Cn $ComputerName -BufferSize 16 -Count 2 -ea 0 -quiet)){
    $rError = "Failed to Ping Device"
    [System.Windows.Forms.MessageBox]::Show($rError , "ERROR")
    Break
}

#Prebuild result form
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

$button1 = New-Object System.Windows.Forms.Button
$label1 = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$button1_OnClick=
{
    LoadForm($ComputerName)
}
$OnLoadForm_StateCorrection=
{
    $rform1.WindowState = $InitialFormWindowState
}


$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 237
$System_Drawing_Point.Y = 270
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 125
$button1.visible = $true
$button1.Size = $System_Drawing_Size
$button1.Name = "button1"
$button1.UseVisualStyleBackColor = $True
$button1.Text = "Refresh"
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($button1_OnClick)
$System_Drawing_Point2 = New-Object System.Drawing.Point
$System_Drawing_Point2.X = 150
$System_Drawing_Point2.Y = 240
$System_Drawing_Size2 = New-Object System.Drawing.Size
$System_Drawing_Size2.Height = 23
$System_Drawing_Size2.Width = 300
$label1.TextAlign = "MiddleCenter"
$label1.TabIndex = 1
#$label1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,1,1)
$label1.Size = $System_Drawing_Size2
$label1.Name = "RefreshTime"
$label1.Visible = $True
$label1.Text = "Never Refreshed"
$label1.Location = $System_Drawing_Point2
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$rform1 = New-Object System.Windows.Forms.Form
$rform1.AutoScaleMode = 0
$rform1.Text = "Results...."
$rform1.DataBindings.DefaultDataSourceUpdateMode = 0
$rSystem_Drawing_Size = New-Object System.Drawing.Size
$rSystem_Drawing_Size.Height = 300
$rSystem_Drawing_Size.Width = 600
$rform1.ClientSize = $rSystem_Drawing_Size
$rform1.FormBorderStyle = 1
$rform1.Name = "Results"
$rform1.width = 600
#$rform1.visible = $True

$rSDP_Result = New-Object System.Drawing.Point
$rSDP_Result.X = 0
$rSDP_Result.Y = 21
$rDataGrid1 = New-Object System.Windows.Forms.DataGridview
$rDataGrid1.Location = $rSDP_Result
$rDataGrid1.Height = 180
$rDataGrid1.Width = 580
$rDataGrid1.TabIndex = 0

$rDataGrid1.visible = $true

$table = new-object System.Data.dataTable
$table.columns.Add("Advertisement ID")
$table.columns.Add("ProgramID")
$table.columns.Add("State")
$table.columns.Add("ContentID")
$table.columns.Add("ExecutionRequestID")
$InitialFormWindowState = $rform1.WindowState
$rform1.add_Load($OnLoadForm_StateCorrection)


$rform1.Add_Shown({
    LoadForm($ComputerName)     
})

$rform1.ShowDialog() | Out-Null

break
Jul 8, 2013 at 8:21 PM
Script 2:

Collection - Safe Reboot
function Expand-String 
{ 
   param( 
       [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] 
       [System.String]$Value, 

       [switch]$EnvironmentVariable 
   )

   if($EnvironmentVariable) { 
      [System.Environment]::ExpandEnvironmentVariables($Value) 
   } 
   else 
   { 
      $ExecutionContext.InvokeCommand.ExpandString($Value) 
   } 
} 

Function Get-RebootFromSCCM($Computer){
$CCMClientSDK = $null 
            $CCMSplat = @{ 
                NameSpace='ROOT\ccm\ClientSDK' 
                Class='CCM_ClientUtilities' 
                Name='DetermineIfRebootPending' 
                ComputerName=$Computer 
                ErrorAction='SilentlyContinue' 
                } 
            $CCMClientSDK = Invoke-WmiMethod @CCMSplat 
            If ($CCMClientSDK) 
            { 
                If ($CCMClientSDK.ReturnValue -ne 0) 
                      { 
                        $message = "Client returned error code $($CCMClientSDK.ReturnValue)" 
                        $reboot = $false
                        $global:reboot=$reboot
                      }#End If ($CCMClientSDK -and $CCMClientSDK.ReturnValue -ne 0) 
 
                If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) 
                    { 
                        $message = "Client waiting for reboot"
                        $reboot = $true
                        $global:reboot=$reboot
                    }else{
                        $message = "Client does not need a reboot for software updates"
                        $reboot = $false
                        $global:reboot=$reboot
                    }
 
            }#End If ($CCMClientSDK) 
            Else 
            { 
                $message = "Unable to get reboot information from client"
                $reboot = $false
                $global:reboot=$reboot
            }  
            $global:message=$message
}
Function Get-UserLoggedIn($computer){
    #RDP Users
    Try{
        $colWMI = Get-WmiObject -Class win32_process -ComputerName $computer -Filter "Name = 'explorer.exe'"
        Foreach($objWMI in $colWMI){
            $global:UserLoggedOn=$True
            $global:message="User is logged in"
        }
    }Catch [System.Exception]{
        $global.message="Unable to connect to WMI"
    }
}
Function LoadForm($ColName){
    
    $smsgui = Expand-String -Value "%SMS_ADMIN_UI_PATH%" -EnvironmentVariable 
    $configmgrconsole = "${smsgui}\..\" 
    $configmgrconsole | set-location
    $configmgrconsole = $configmgrconsole + '\ConfigurationManager.psd1'
    import-module ($configmgrconsole)
    cd ccm:


    Get-CMDevice -CollectionName $ColName | Where-object {$_.IsClient -eq $True} | Select-Object -Property Name | Foreach {

        $Computer = $_.Name
        #If you can ping it
        If(Test-Connection -Cn $_.Name -BufferSize 16 -Count 1 -ea 0 -quiet){
            #If it has been on for 30 minutes or more
            if(((Get-Date) - ([System.Management.ManagementDateTimeconverter]::ToDateTime((Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer).LastBootUpTime))).TotalMinutes -gt 30){
                    $global:reboot=$false
                    $global:message=""
                    $global:UserLoggedOn=$false
                    Get-RebootFromSCCM($Computer)
                    #If the computer needs a reboot
                    If ($reboot -eq $true){
                        Get-UserLoggedIn($Computer)
                        #If there is no user logged in
                        If($UserLoggedOn -eq $false){
                            #Reboot
                            shutdown -r -f -t 0
                            $message = "Restart sent."
                        }else{
                            $message = "User Logged on"
                        }
                    }else{
                        $message = "Restart not required"
                    }
            }else{
                $message = "Uptime is less than 30 minutes...not restarting"
            }
        }else{
            $message = "Could not ping"
        }
        $resultrow = @(($Computer),($message))
        $table.Rows.Add($resultrow)
        $rform1.refresh()
    }
    $label1.Text = "Complete"
    $rform1.Refresh()

}

$ColName = $args[0] 

If (!$ColName) {
    [System.Windows.Forms.MessageBox]::Show("Invalid Collection" , "ERROR")
    Break
}else{
    write-host $ColName
}

#Prebuild result form
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$OnLoadForm_StateCorrection=
{
    $rform1.WindowState = $InitialFormWindowState
}


$rform1 = New-Object System.Windows.Forms.Form
$rform1.AutoScaleMode = 0
$rform1.Text = "Results...."
$rform1.DataBindings.DefaultDataSourceUpdateMode = 0
$rSystem_Drawing_Size = New-Object System.Drawing.Size
$rSystem_Drawing_Size.Height = 300
$rSystem_Drawing_Size.Width = 300
$rform1.ClientSize = $rSystem_Drawing_Size
$rform1.FormBorderStyle = 1
$rform1.Name = "Results"
$rform1.width = 300
#$rform1.visible = $True

$rSDP_Result = New-Object System.Drawing.Point
$rSDP_Result.X = 15
$rSDP_Result.Y = 21
$rDataGrid1 = New-Object System.Windows.Forms.DataGridview
$rDataGrid1.Location = $rSDP_Result
$rDataGrid1.Height = 180
$rDataGrid1.Width = 260
$rDataGrid1.TabIndex = 0
$rDataGrid1.visible = $true
$table = new-object System.Data.dataTable
$table.columns.Add("Computer")
$table.columns.Add("Result")
$InitialFormWindowState = $rform1.WindowState
$rform1.add_Load($OnLoadForm_StateCorrection)
$rDataGrid1.DataSource = $table

$label1 = New-Object System.Windows.Forms.Label
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 95
$System_Drawing_Point.Y = 240
$label1.Location = $System_Drawing_Point
$label1.width = 100
$label1.TextAlign = "MiddleCenter"
$label1.TabIndex = 1
#$label1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,1,1)
$label1.Size = $System_Drawing_Size2
$label1.Name = "Status"
$label1.Visible = $True
$label1.Text = "Working...."
$label1.Location = $System_Drawing_Point2
$label1.DataBindings.DefaultDataSourceUpdateMode = 0


$rform1.Controls.Add($rDataGrid1)
$rform1.Controls.Add($label1)


$rform1.Add_Shown({
    LoadForm($ColName)      
})

$rform1.ShowDialog() | Out-Null

break
Jul 8, 2013 at 8:24 PM
Script 3:

Collection - ReRun Advertisement (part 1)

function Expand-String 
{ 
   param( 
       [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] 
       [System.String]$Value, 

       [switch]$EnvironmentVariable 
   )

   if($EnvironmentVariable) { 
      [System.Environment]::ExpandEnvironmentVariables($Value) 
   } 
   else 
   { 
      $ExecutionContext.InvokeCommand.ExpandString($Value) 
   } 
} 

function is64bit($ComputerName)
{
$procarch = Get-WmiObject -class Win32_Processor -property AddressWidth -ComputerName $ComputerName | select-object Addresswidth | Format-table -HideTableHeaders | out-string
$procarch = $procarch  -replace '\n', ''
$procarch = $procarch  -replace '\s', ''
    If ($procarch -eq "64"){
        return $true
    }Else{
        return $false
    }
}

function LoadForm(){

}

$ColName = $args[0] 
$global:cancel = $false

If (!$ColName) {
    [System.Windows.Forms.MessageBox]::Show("Invalid Collection" , "ERROR")
    Break
}else{
    write-host $ColName
}
$global:SelObj = ""

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$label1 = New-Object System.Windows.Forms.Label
$comboBox1 = New-Object System.Windows.Forms.ComboBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.

$button1_OnClick=
{
$global:SelObj = $comboBox1.SelectedItem
$form1.close()
}
$handler_label2_Click=
{
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState

}
#----------------------------------------------
#region Generated Form Code
$form1.AutoScaleMode = 0
$form1.Text = "Please wait loading Deployment...."
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 120
$System_Drawing_Size.Width = 500
$form1.ClientSize = $System_Drawing_Size
$form1.FormBorderStyle = 1

$form1.Controls.Add($InfoLabel)

$button1.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 125
$button1.Size = $System_Drawing_Size
$button1.Name = "button1"
$button1.UseVisualStyleBackColor = $True
$button1.Visible = $True
$button1.Text = "OK"
$button2.Size = $System_Drawing_Size
$button2.Name = "button2"
$button2.UseVisualStyleBackColor = $True
$button2.Visible = $True
$button2.Text = "Cancel"
$button2.TabIndex = 6   
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 100
$System_Drawing_Point.Y = 44
$System_Drawing_Point2 = New-Object System.Drawing.Point
$System_Drawing_Point2.X = 300
$System_Drawing_Point2.Y = 44
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($button1_OnClick)
$button2.Location = $System_Drawing_Point2
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click({        
    $ProcessID = [System.Diagnostics.Process]::GetCurrentProcess()
    $ProcID = $ProcessID.ID
    & taskkill /PID $ProcID /T /F
})
$form1.Controls.Add($button1)
$form1.Controls.Add($button2)
$label1.TabIndex = 1
$label1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,1)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 110
$label1.Size = $System_Drawing_Size
$label1.Name = "label1"
$label1.Visible = $True
$label1.Text = "Deployment:"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 26
$label1.Location = $System_Drawing_Point
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Controls.Add($label1)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 125
$System_Drawing_Point.Y = 21
$comboBox1.Location = $System_Drawing_Point
$comboBox1.Visible = $False
$comboBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$comboBox1.FormattingEnabled = $True
$comboBox1.Name = "comboBox1"
$comboBox1.TabIndex = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 375
$comboBox1.Size = $System_Drawing_Size
$form1.Controls.Add($comboBox1)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
$form1.Add_Shown({
    $smsgui = Expand-String -Value "%SMS_ADMIN_UI_PATH%" -EnvironmentVariable 
    $configmgrconsole = "${smsgui}\..\" 
    $configmgrconsole | set-location
    $configmgrconsole = $configmgrconsole + '\ConfigurationManager.psd1'
    import-module ($configmgrconsole)
    cd ccm:

    $Object = Get-CMDeployment -CollectionName $ColName | Select-Object -Property SoftwareName,DeploymentID
    $Object | Foreach {
        $comboBox1.items.add($_.SoftwareName+", DeploymentID:"+$_.DeploymentID)
        $comboBox1.SelectedIndex=0
    }
    $form1.Text = "Please Select a Deployment"

    $Combobox1.visible = $true
    $form1.Refresh()
})

#Show the Form
$form1.ShowDialog()| Out-Null
$SelArray = $SelObj -split "DeploymentID:"
$DepID = $SelArray[1]

If (!$DepID) {
    [System.Windows.Forms.MessageBox]::Show("Invalid Deployment" , "ERROR")
    Break
}

#Prebuild result form

[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$rform1 = New-Object System.Windows.Forms.Form
$rform1.AutoScaleMode = 0
$rform1.Text = "Working...."
$rform1.DataBindings.DefaultDataSourceUpdateMode = 0
$rSystem_Drawing_Size = New-Object System.Drawing.Size
$rSystem_Drawing_Size.Height = 300
$rSystem_Drawing_Size.Width = 300
$rform1.ClientSize = $rSystem_Drawing_Size
$rform1.FormBorderStyle = 1
$rform1.Name = "Results"
$rSDP_Result = New-Object System.Drawing.Point
$rSDP_Result.X = 21
$rSDP_Result.Y = 21
$rDataGrid1 = New-Object System.Windows.Forms.DataGridview
$rDataGrid1.Location = $rSDP_Result
$rDataGrid1.Height = 250
$rDataGrid1.Width = 258
$rDataGrid1.Columns(0).Width = 150
$rDataGrid1.Columns(1).Width = 150


#$rDataGrid1.DataBindings.DefaultDataSourceUpdateMode = 0
$rDataGrid1.HeaderForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
#$rDataGrid1.Items.Add('Result')
$rDataGrid1.visible = $true
#$rbutton1.Add_Click($rform1.close())

$table = new-object System.Data.dataTable
$table.columns.Add("Computer Name")
$table.columns.Add("Result")

$rError = ""
$success = ""

$rDataGrid1.DataSource = $table
$rform1.Controls.Add($rDataGrid1)

Jul 8, 2013 at 8:25 PM
Script 3:

Collection - ReRun Advertisement (part 2)

$rform1.Add_Shown({
    $PackageID = Get-CMDeployment -DeploymentID $DepID | Select-Object PackageID | Format-Table -HideTableHeaders | out-string
    $PackageID = $PackageID -replace '\s', ''
    $PackageID = $PackageID -replace '\n', ''
    $ProgramName = Get-CMDeployment -DeploymentID $DepID | Select-Object ProgramName | Format-Table -HideTableHeaders | out-string
    $ProgramName = $ProgramName -replace '\n', ''
    $ProgramName = $ProgramName -replace '\s', ''

    #Get the Devices in the collection
    Get-CMDevice -CollectionName $ColName | Where-object {$_.IsClient -eq $True} | Select-Object -Property Name | Foreach {
        #If you can ping it
        $ComputerName = $_.Name
        $success = ""
        $rError = ""
        If(Test-Connection -Cn $_.Name -BufferSize 16 -Count 2 -ea 0 -quiet){
            #Delete the history from the registry
            If ($ProgramName -notcontains '*') {
                If (is64bit($ComputerName)){
                    #constant for the HLKM    
                    $HKLM = "&h80000002"   
                    #creates an SwbemNamedValueSet object  
                    $objNamedValueSet = New-Object -COM "WbemScripting.SWbemNamedValueSet"   
                    #adds the actual value that will requests the target to provide 64bit-registry info  
                    $objNamedValueSet.Add("__ProviderArchitecture", 64) | Out-Null   
                    #back to all the other usual COM objects for WMI that you have used a zillion times in VBScript  
                    $objLocator = New-Object -COM "Wbemscripting.SWbemLocator"   
                    $objServices = $objLocator.ConnectServer($ComputerName,"root\default","","","","","",$objNamedValueSet)    
                    $objStdRegProv = $objServices.Get("StdRegProv")    
                    # Obtain an InParameters object specific to the method.    
                    $Inparams = ($objStdRegProv.Methods_ | where {$_.name -eq "EnumKey"}).InParameters.SpawnInstance_()    
                    # Add the input parameters    
                    $regkey = "SOFTWARE\\Microsoft\\SMS\\Mobile Client\\Software Distribution\\Execution History\\System"
                    ($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $HKLM   
                    ($Inparams.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = $regkey   
                    
                    #Execute the method    
                    $Outparams = $objStdRegProv.ExecMethod_("EnumKey", $Inparams, "", $objNamedValueSet)    
                   
                    #Get the Subkeys    
                    $SubKeys = ($Outparams.Properties_ | where {$_.name -eq "sNames"}).Value    
                    
                    Foreach($subkey in $subkeys){
                        If ($packageID -eq ($subkey)){
                            $Inparams2 = ($objStdRegProv.Methods_ | where {$_.name -eq "EnumKey"}).InParameters.SpawnInstance_()   
                            ($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $HKLM                   
                            ($Inparams2.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = $regkey+"\\"+$subkey   
                            $Outparams2 = $objStdRegProv.ExecMethod_("EnumKey", $Inparams2, "", $objNamedValueSet) 
                            $SubKeys2 = ($Outparams2.Properties_ | where {$_.name -eq "sNames"}).Value
                            Foreach ($subkey2 in $subkeys2){
                                $Inparams3 = ($objStdRegProv.Methods_ | where {$_.name -eq "GetStringValue"}).InParameters.SpawnInstance_() 
                                ($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $HKLM   
                                ($Inparams3.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = "$regkey\\$subkey\\$subkey2"
                                ($Inparams3.Properties_ | where {$_.name -eq "Svaluename"}).Value = "_ProgramID"  
                                $Outparams3 = $objStdRegProv.ExecMethod_("GetStringValue", $Inparams3, "", $objNamedValueSet) 
                                $registryProg = ($Outparams3.Properties_ | where {$_.name -eq "sValue"}).Value
                                #$registryProg = $registryProg -replace '\s', ''
                                $registryProg = $registryProg -replace '\s', ''
                                $registryProg = $registryProg -replace '\n', ''
                                If($ProgramName -eq $registryProg){
                                
                                    $Inparams4 = ($objStdRegProv.Methods_ | where {$_.name -eq "DeleteKey"}).InParameters.SpawnInstance_() 
                                    ($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $HKLM   
                                    ($Inparams4.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = $regkey+"\\"+$subkey+"\\"+$subkey2   
                                    $Outparams4 = $objStdRegProv.ExecMethod_("DeleteKey", $Inparams4, "", $objNamedValueSet) 
                                    $return = ($Outparams.Properties_ | where {$_.name -eq "ReturnValue"}).Value  
                                    $success = "Deleted key:$subkey2"
                                    
                                }
                            }
                        }
                    }
                   
                
                    
                }else{
                    #$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
                    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
                    
                    $RegKey= $Reg.OpenSubKey("SOFTWARE\\Microsoft\\SMS\\Mobile Client\\Software Distribution\\Execution History\\System")
                    foreach($subkeyName in $RegKey.GetSubKeyNames()){
                        
                        If ($packageID.contains($subKeyName)){
                            $RegKey2 = $RegKey.OpenSubKey($subKeyName,$true)
                            foreach($subkeyName2 in $RegKey2.GetSubKeyNames()){
                                write-host $subkeyName2
                                $subkey2 = $RegKey2.OpenSubKey($subkeyName2,$true)
                                $registryProg = $subkey2.GetValue("_ProgramID")
                                $registryProg = $registryProg -replace '\s', ''
                                write-host $ProgramName
                                write-host $registryProg
                                If($ProgramName -contains $registryProg ){
                                    $RegKey2.DeleteSubKeyTree($subkeyName2)
                                    $success = "Deleted key:$subkeyName2"
                                    
                                }
                            }
                            
                        }
                    }
                }
            }
                
            #Delete the history from the WMI
            $wmiObject = Get-WmiObject -class CCM_Scheduler_History -NameSpace "root\ccm\scheduler" -ComputerName $ComputerName -filter "ScheduleID like '%$DepID%-%$PackageID%'"
            If($wmiObject){
            Remove-WmiObject -InputObject $wmiObject

            $rError = ""
            $success = "Deleted from wmi history"
            
            } else {
                if($success -ne ""){
                $success = "Failed to find in WMI, but found in registry. "  + $success
                }
            }
            
        }else{
            $rError = "Failed to Ping"
        }
        If ($success -eq ""){
            If($rError -eq ""){
                $rError = "No Advertisement Found"
            }
        }else{
        $rError = $success
        
        #restart SMS Agent service
        $service = get-service -ComputerName $ComputerName -Name ccmexec
        Restart-Service -InputObject $service
        }
        $resultrow = @(($ComputerName),($rError))
        $table.Rows.Add($resultrow)
        $rform1.refresh()
    }
    Get-CMDevice -CollectionName $ColName | Where-object {$_.IsClient -ne $True} | Select-Object -Property Name | Foreach {
        
        $resultrow = @(($_.Name),("No Client"))
        $table.Rows.Add($resultrow)
        $rform1.refresh()
    }
    $rForm1.Text="Complete"
    $rForm1.Refresh()
    
})




$rform1.ShowDialog() | Out-Null


break
Jul 8, 2013 at 8:26 PM
Script 4:

Device - Install Missing Updates
#Get Arguments
$ResourceID = $args[0]
$Server = $args[1]
$Namespace = $args[2]

$strQuery = "Select ResourceID,ResourceNames from SMS_R_System where ResourceID='$ResourceID'"
Get-WmiObject -Query $strQuery -Namespace $Namespace -ComputerName $Server | ForEach-Object {$CompName = $_.ResourceNames[0]}

$objpopup = new-object -comobject wscript.shell

If (test-connection -computername $CompName -count 1 -quiet){
    $Error.Clear()
    $MissingUpdates = @(Get-WmiObject -ComputerName $CompName -Class CCM_SoftwareUpdate -Filter ComplianceState=0 -Namespace root\CCM\ClientSDK | Foreach-Object {[WMI]$_.__PATH})
    $returncode = Invoke-WmiMethod -ComputerName $CompName -Class CCM_SoftwareUpdatesManager -Name InstallUpdates -ArgumentList (,$MissingUpdates) -Namespace root\ccm\ClientSDK
    if($returncode.ReturnValue -eq 0){
        $actualpopup = $objpopup.popup("Software Update installation successfully triggered on $CompName",0,”Results”,0)
    }else{
        $errorcode = $returncode.ReturnValue
        $actualpopup = $objpopup.popup("Software Update installation returned code: $errorcode on $CompName",0,”Results”,16)
    }
}
else {$actualpopup = $objpopup.popup(“$CompName is not on“,0,”Results”,16)}
Jun 12, 2014 at 2:03 PM
Hi mdeboer,

could you guide me hot to add your scripts to this CM12 tool?

thanks