Skip to content

Instantly share code, notes, and snippets.

@danjpadgett
Created August 23, 2016 10:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danjpadgett/6122c7b2231e1f104842ef2f0077ad24 to your computer and use it in GitHub Desktop.
Save danjpadgett/6122c7b2231e1f104842ef2f0077ad24 to your computer and use it in GitHub Desktop.
#region Control Helper Functions
function Load-DataGridView
{
Param (
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[System.Windows.Forms.DataGridView]$DataGridView,
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
$Item,
[Parameter(Mandatory=$false)]
[string]$DataMember
)
Load-DataGridView -DataGridView $datagridviewResults -Item
$DataGridView.SuspendLayout()
$DataGridView.DataMember = $DataMember
if ($Item -is [System.ComponentModel.IListSource]`
-or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView] )
{
$DataGridView.DataSource = $Item
}
else
{
$array = New-Object System.Collections.ArrayList
if ($Item -is [System.Collections.IList])
{
$array.AddRange($Item)
}
else
{
$array.Add($Item)
}
$DataGridView.DataSource = $array
}
$DataGridView.ResumeLayout()
}
function ConvertTo-DataTable
{
[OutputType([System.Data.DataTable])]
param(
[ValidateNotNull()]
$InputObject,
[ValidateNotNull()]
[System.Data.DataTable]$Table,
[switch]$RetainColumns,
[switch]$FilterWMIProperties)
if($Table -eq $null)
{
$Table = New-Object System.Data.DataTable
}
if($InputObject-is [System.Data.DataTable])
{
$table = ConvertTo-DataTable -InputObject $processes –FilterWMIProperties
}
else
{
if(-not $RetainColumns -or $Table.Columns.Count -eq 0)
{
#Clear out the Table Contents
$Table.Clear()
if($InputObject -eq $null){ return } #Empty Data
$object = $null
#find the first non null value
foreach($item in $InputObject)
{
if($item -ne $null)
{
$object = $item
break
}
}
if($object -eq $null) { return } #All null then empty
#Get all the properties in order to create the columns
foreach ($prop in $object.PSObject.Get_Properties())
{
if(-not $FilterWMIProperties -or -not $prop.Name.StartsWith('__'))#filter out WMI properties
{
#Get the type from the Definition string
$type = $null
if($prop.Value -ne $null)
{
try{ $type = $prop.Value.GetType() } catch {}
}
if($type -ne $null) # -and [System.Type]::GetTypeCode($type) -ne 'Object')
{
[void]$table.Columns.Add($prop.Name, $type)
}
else #Type info not found
{
[void]$table.Columns.Add($prop.Name)
}
}
}
if($object -is [System.Data.DataRow])
{
foreach($item in $InputObject)
{
$Table.Rows.Add($item)
}
return @(,$Table)
}
}
else
{
$Table.Rows.Clear()
}
foreach($item in $InputObject)
{
$row = $table.NewRow()
if($item)
{
foreach ($prop in $item.PSObject.Get_Properties())
{
if($table.Columns.Contains($prop.Name))
{
$row.Item($prop.Name) = $prop.Value
}
}
}
[void]$table.Rows.Add($row)
}
}
return @(,$Table)
}
#endregion
$sccmserver = "wokintm107.intu.group"
$searchbase = "OU=Workstations,OU=Root,DC=intu,DC=group"
#$C = Get-Credential
Function GetSCCMResourceID
{
$compObject = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$selecteditem'" -computername $sccmserver -namespace "ROOT\SMS\site_INU"
Write-Output $compObject
}
Function RemoveSCCMResourceID
{
return $compObject = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$datagridviewResults_CellContentClick'" -computername $sccmserver -namespace "ROOT\SMS\site_INU"
}
#region Search Function
function SearchGrid()
{
$RowIndex = 0
$ColumnIndex = 0
$seachString = $textboxSearch.Text
if($seachString -eq "")
{
return
}
if($datagridviewResults.SelectedCells.Count -ne 0)
{
$startCell = $datagridviewResults.SelectedCells[0];
$RowIndex = $startCell.RowIndex
$ColumnIndex = $startCell.ColumnIndex + 1
}
$columnCount = $datagridviewResults.ColumnCount
$rowCount = $datagridviewResults.RowCount
for(;$RowIndex -lt $rowCount; $RowIndex++)
{
$Row = $datagridviewResults.Rows[$RowIndex]
for(;$ColumnIndex -lt $columnCount; $ColumnIndex++)
{
$cell = $Row.Cells[$ColumnIndex]
if($cell.Value -ne $null -and $cell.Value.ToString().IndexOf($seachString, [StringComparison]::OrdinalIgnoreCase) -ne -1)
{
$datagridviewResults.CurrentCell = $cell
return
}
}
$ColumnIndex = 0
}
$datagridviewResults.CurrentCell = $null
[void][System.Windows.Forms.MessageBox]::Show("The search has reached the end of the grid.","String not Found")
}
#endregion
$formMain_Load={
#TODO: Initialize Form Controls here
}
#region MainCode
$computers = Get-ADComputer -Filter * -property name, Description -SearchBase $searchbase | select name, Description
#endregion
$buttonExit_Click={
#TODO: Place custom script here
$formMain.Close()
}
$buttonSearch_Click = {
Load-DataGridView -DataGridView $datagridviewResults -Item $computers
$toolstripstatuslabel1.Text = "Select Object"
$toolstripprogressbar1.Increment(50)
SearchGrid
}
$datagridviewResults_ColumnHeaderMouseClick=[System.Windows.Forms.DataGridViewCellMouseEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.DataGridViewCellMouseEventArgs]
if($datagridviewResults.DataSource -is [System.Data.DataTable])
{
$column = $datagridviewResults.Columns[$_.ColumnIndex]
$direction = [System.ComponentModel.ListSortDirection]::Ascending
if($column.HeaderCell.SortGlyphDirection -eq 'Descending')
{
$direction = [System.ComponentModel.ListSortDirection]::Descending
}
$datagridviewResults.Sort($datagridviewResults.Columns[$_.ColumnIndex], $direction)
}
}
$formMain_FormClosed=[System.Windows.Forms.FormClosedEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.FormClosedEventArgs]
#Stop any pending jobs
Stop-JobTracker
}
$timerJobTracker_Tick={
Update-JobTracker
}
#region Job Tracker
$JobTrackerList = New-Object System.Collections.ArrayList
function Add-JobTracker
{
Param(
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[string]$Name,
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[ScriptBlock]$JobScript,
$ArgumentList = $null,
[ScriptBlock]$CompletedScript,
[ScriptBlock]$UpdateScript)
#Start the Job
$job = Start-Job -Name $Name -ScriptBlock $JobScript -ArgumentList $ArgumentList
if($job -ne $null)
{
#Create a Custom Object to keep track of the Job & Script Blocks
$members = @{ 'Job' = $Job;
'CompleteScript' = $CompletedScript;
'UpdateScript' = $UpdateScript}
$psObject = New-Object System.Management.Automation.PSObject -Property $members
[void]$JobTrackerList.Add($psObject)
#Start the Timer
if(-not $timerJobTracker.Enabled)
{
$timerJobTracker.Start()
}
}
elseif($CompletedScript -ne $null)
{
#Failed
Invoke-Command -ScriptBlock $CompletedScript -ArgumentList $null
}
}
function Update-JobTracker
{
<#
.SYNOPSIS
Checks the status of each job on the list.
#>
#Poll the jobs for status updates
$timerJobTracker.Stop() #Freeze the Timer
for($index =0; $index -lt $JobTrackerList.Count; $index++)
{
$psObject = $JobTrackerList[$index]
if($psObject -ne $null)
{
if($psObject.Job -ne $null)
{
if($psObject.Job.State -ne "Running")
{
#Call the Complete Script Block
if($psObject.CompleteScript -ne $null)
{
#$results = Receive-Job -Job $psObject.Job
Invoke-Command -ScriptBlock $psObject.CompleteScript -ArgumentList $psObject.Job
}
$JobTrackerList.RemoveAt($index)
Remove-Job -Job $psObject.Job
$index-- #Step back so we don't skip a job
}
elseif($psObject.UpdateScript -ne $null)
{
#Call the Update Script Block
Invoke-Command -ScriptBlock $psObject.UpdateScript -ArgumentList $psObject.Job
}
}
}
else
{
$JobTrackerList.RemoveAt($index)
$index-- #Step back so we don't skip a job
}
}
if($JobTrackerList.Count -gt 0)
{
$timerJobTracker.Start()#Resume the timer
}
}
function Stop-JobTracker
{
<#
.SYNOPSIS
Stops and removes all Jobs from the list.
#>
#Stop the timer
$timerJobTracker.Stop()
#Remove all the jobs
while($JobTrackerList.Count -gt 0)
{
$job = $JobTrackerList[0].Job
$JobTrackerList.RemoveAt(0)
Stop-Job $job
Remove-Job $job
}
}
#endregion
$buttonRemoveAD_Click = {
$selecteditem = $($datagridviewResults.CurrentCell.Value.ToString())
Write-Host $selecteditem
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$msgboxwarning = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to remove '$selecteditem'' from AD?", "Confirm Removal", 0)
if ($msgboxwarning -eq "OK")
{
Remove-ADComputer -Identity $selecteditem
}
else
{ }
}
$textboxSearch_KeyDown=[System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
if($_.KeyCode -eq 'Enter' -and $buttonSearch.Enabled)
{
SearchGrid
$_.SuppressKeyPress = $true
}
}
$buttonRemoveSCCMObj_Click = {
$selecteditem = $($datagridviewResults.CurrentCell.Value.ToString())
Write-Host $selecteditem
$progressbar1.PerformStep()
$compObject = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$selecteditem'" -computername $sccmserver -namespace "ROOT\SMS\site_INU"
Write-Host $compObject
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$msgboxwarning = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to remove '$selecteditem'' - SCCM Resource ID :$($compObject.ResourceID)" , "Confirm Removal", 0)
if ($msgboxwarning -eq "OK")
{
$compObject.psbase.delete()
}
else
{}
}
$datagridviewResults_CellContentClick=[System.Windows.Forms.DataGridViewCellEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.DataGridViewCellEventArgs]
#TODO: Place custom script here
}
$buttonRemoveBoth_Click= {
$selecteditem = $($datagridviewResults.CurrentCell.Value.ToString())
$compObject = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$selecteditem'" -computername $sccmserver -namespace "ROOT\SMS\site_INU"
Write-Host $selecteditem
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$msgboxwarning = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to remove '$selecteditem'' - SCCM Resource ID : $($compObject.ResourceID) & from AD", "Confirm Removal", 0)
if ($msgboxwarning -eq "OK")
{
$compObject.psbase.delete()
Remove-ADComputer -Identity $selecteditem
}
}
$textboxSearch_TextChanged={
#TODO: Place custom script here
}
$Refresh_Click={
#TODO: Place custom script here
$datagridviewResults.Refresh()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment