Powershell Checkbox Issue

Hi,

I have created the Disk cleanup GUI SCRIPT in Powershell v2,

When I run the script , it will show the C drive files  n the result panel, I have a check box in the result page to finalize what are the files I want to delete ,

After I click check box, I have to click Okay button to delete the files or cancel  the operation

After clicking OKay button, the new popup window will come to the front and display the full files path details what I have selected In the result page, If ill click Confirm button in the popup page it will delete the files or cancel button to cancel the action.

Problem:

If I select some folders checkbox in the result page and click okay button it will show what I have selected but If I cancel the operation then uncheck some folders  then click Okay button that time it will show unchecked files and  duplicating the  values again and again ,

Please help me to moving forward , Thanks!

August 31st, 2015 12:27am

Sorry. We cannot guess at what you are doing or asking.  It is not possible to know what your problem is.  What popup? PowerShell has not popups. Are you trying to use Windows Forms. Perhaps you should read the following articles:

https://www.sapien.com/blog/topics/user-interface-design-for-administrators/

Free Windows Admin Tool Kit Click here and download it now
August 31st, 2015 1:25am

Yep,

show us some code then we will probably find the error.

Duplicating files sounds like you did not clear the previous list accuratly when showing the list. But without detailed information this is just guessing.

August 31st, 2015 4:30am

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$ErrorActionPreference = "SilentlyContinue"

 

Function Add-Node($Nodes, $Path)
{
  $Path.Split("/") | %{
    Write-Verbose "Searching For: $_"
    $SearchResult = $Nodes.Find($_, $False)
    If ($SearchResult.Count -eq 1)
    {
      Write-Verbose "Selecting: $($SearchResult.Name)"
      # Must select first element. Return from Find is TreeNode[]
      $Nodes = $SearchResult[0].Nodes
    }
    Else
    {
      Write-Verbose "Adding: $_"
      $Node = New-Object Windows.Forms.TreeNode($_)
      # Name must be populated for Find work
      $Node.Name = $_
      $Nodes.Add($Node)
    }
  }
}

 

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "C Drive Automation"
$objForm.Size = New-Object System.Drawing.Size(600,1000)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$dGViewDrive = New-Object System.Windows.Forms.DataGridView -Property @{
    Location = New-Object System.Drawing.Size(10,80)
    Size=New-Object System.Drawing.Size(500,80)
    ColumnHeadersVisible = $true
   
 
}
$objForm.Controls.Add($dGViewDrive)


$dataGridView = New-Object System.Windows.Forms.DataGridView -Property @{
    Location = New-Object System.Drawing.Size(10,220)
    Size=New-Object System.Drawing.Size(500,400)
    ColumnHeadersVisible = $true
   
 
}

$Label = New-Object System.Windows.Forms.Label

$Label.Text = "testing only -- files shown here are more than 1 month old for C:\temp Dir."


$Label.Location=New-Object System.Drawing.Size(10,185)
$Label.AutoSize = $True

$objForm.Controls.Add($Label)

 


$TreeView = New-Object Windows.Forms.TreeView

$TreeView.PathSeparator = "/"
$TreeView.CheckBoxes = $true


$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 524
$System_Drawing_Size.Height = 563
$TreeView.Size = $System_Drawing_Size

$TreeView.Location=New-Object System.Drawing.Size(10,230)

$listToDelete = New-Object System.collections.ArrayList


$TV_AfterCheck =
{
 if($_.Node.Checked)
 {

 $n=$_.Node

 $file=$n.Text

 while($n.Text -ne "")
 {

    $n=$n.Parent

    $file= $n.Text +'\' +$file
 }

 $listToDelete.Add($file)

 }
 else
 {
  $n=$_.Node

 $file=$n.Text

 while($n.Text -ne "")
 {

    $n=$n.Parent

    $file= $n.Text +'\' +$file
 }


 $listToDelete.Remove($file)
 }
}

$TreeView.Add_AfterCheck($TV_AfterCheck)

 

$objForm.Controls.Add($TreeView)

 

 

$Column1 = New-Object System.Windows.Forms.DataGridViewCheckBoxColumn
    $Column1.width = 10
    $Column1.name = "Select"
    $dataGridView.Columns.Add($Column1)


$dataGridView.sel

$objForm.Controls.Add($dataGridView)


$list = New-Object System.collections.ArrayList

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(200,40)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "FETCH"
$OKButton.Add_Click(
{
$x=$objTextBox.Text;

$drive=get-wmiobject Win32_LogicalDisk -ComputerName  -Filter "DriveType=3" | select Name,FreeSpace,BlockSize,Size | % {$_.BlockSize=(($_.FreeSpace)/($_.Size))*100;$_.FreeSpace=($_.FreeSpace/1GB);$_.Size=($_.Size/1GB);$_}
$listdrive = New-Object System.collections.ArrayList
$listdrive.AddRange($drive)

 

$Eliminate = @("svc*", "sql*", "shr*","sup")

$includelist=@("*adm","*.1")

$includefile=@(".tmp",".corrupt")

$3MonthAgo = [DateTime]::Now.AddMonths(-3)

 

if(Test-Path \\$x'\c$\users')

{

$gps = get-childitem \\$x\c$\users -recurse -include $includelist -exclude $Eliminate | where {  $_.PSIsContainer } | select fullname, lastaccesstime, lastwritetime | where { ! $_.PSIsContainer -and $3MonthAgo -ge $_.LastAccessTime } | select fullname, lastaccesstime, lastwritetime
$list.AddRange($gps)

}


if(Test-Path \\$x'\c$\profile')
    {
    $gps = get-childitem \\$x\c$\profile -recurse -include $includelist -exclude $Eliminate | where {  $_.PSIsContainer } | select fullname, lastaccesstime, lastwritetime | where { ! $_.PSIsContainer -and $3MonthAgo -ge $_.LastAccessTime } | select fullname, lastaccesstime, lastwritetime
    $list.AddRange($gps)
 
    }

    if(Test-Path \\$x'\c$\Documents and Settings' )
    {
    $gps = get-childitem \\$x'\c$\Documents and Settings' -Force -recurse -include $includelist -exclude $Eliminate | where {  $_.PSIsContainer } | select fullname, lastaccesstime, lastwritetime | where { ! $_.PSIsContainer -and $3MonthAgo -ge $_.LastAccessTime } | select fullname, lastaccesstime, lastwritetime
    $list.AddRange($gps)

    }

$1MonthAgo = [DateTime]::Now.AddMonths(-1)

    $gps = Get-ChildItem \\$x\c$\windows\temp -Recurse  | where { $1MonthAgo -ge $_.lastwritetime } | select fullname, lastaccesstime, lastwritetime
    $list.AddRange($gps)


    $gps = Get-ChildItem \\$x\c$\temp -Recurse  | where { $1MonthAgo -ge $_.lastwritetime } | select fullname, lastaccesstime, lastwritetime
    $list.AddRange($gps)


    $gps = Get-ChildItem \\$x\'c$\$Recycle.Bin' -Force | select fullname, lastaccesstime, lastwritetime
    $list.AddRange($gps)

 

[System.Windows.Forms.MessageBox]::Show('total' + $list.Count)

$list | ForEach-Object {

$b = $_.fullname -replace '\\','/'

Add-Node $TreeView.Nodes $b

}

 


})
$objForm.Controls.Add($OKButton)

 


$OKDelete = New-Object System.Windows.Forms.Button
$OKDelete.Location = New-Object System.Drawing.Size(10,800)
$OKDelete.Size = New-Object System.Drawing.Size(75,23)
$OKDelete.Text = "Clean Up"
$OKDelete.Add_Click(
{


Foreach ($file in $listToDelete)

{

$nametocompare="\" + $file

 

$list | ForEach-Object {

$c = $_.fullname

$finalDeletefiles

if($c.StartsWith($nametocompare))
{

$finalDeletefiles = $finalDeletefiles + $c + "`r`n"

 

}


}

 

# Remove-Item $row.Cells[0].Value

}

 

$OUTPUT= [System.Windows.Forms.MessageBox]::Show($finalDeletefiles , "Delete files?" , 4)
if ($OUTPUT -eq "YES" )
{

$option = [System.StringSplitOptions]::RemoveEmptyEntries
 $finaldelete=$finalDeletefiles.Split("`r`n",$option)
 [System.Windows.Forms.MessageBox]::Show($finaldelete.Count)

 
Foreach ($filetoremove in $finaldelete)
{

 
$Answer = Remove-Item $filetoremove -Force -Recurse

            If ( $Answer=$True)

            {

            Write-Host "Files Deleted Successfully"
            }

                Else
                {
                Write-Host "Issue"
                } 

 }


}

})
$objForm.Controls.Add($OKDelete)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please enter server name:"
$objForm.Controls.Add($objLabel)

$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(180,20)

$objTextBox.Text="any"
$objForm.Controls.Add($objTextBox)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

 

 

$x

Free Windows Admin Tool Kit Click here and download it now
September 1st, 2015 1:50am

I have attached the sample code .. please advise me
September 1st, 2015 1:53am

Well,

first some design patterns - dont mix execution code with GUI - make a region where you create all your GUI objects and seperate them. 

Put the Events also in a own region btw region:

#============================
#region GuiObject


#all GUI objects in here

#endregion
#============================


#============================
#region wonderfullEventRegion


#Events in here

#endregion
#============================


#============================
#region functions


#Functions in here

#endregion
#============================

#============================
#region Execution


#Executioncode in here

#endregion
#============================

Even better would be to export some of these in separate files.

Ok - next: 

in $TV_AfterCheck - you have to start with 

$TV_AfterCheck = 
{
if($listToDelete)
{
    $listToDelete.Clear()
}
Probably there are also more errors in it. Try to reorganize your code and test this. If the error persists we will go further on then.

Free Windows Admin Tool Kit Click here and download it now
September 1st, 2015 4:14am

Start  by removing this line: "$ErrorActionPreference = "SilentlyContinue""

Fix all errors next.

September 1st, 2015 5:07am

A quick look at your code shows the syntax is badly broken in a number of places.  The layout of the code shows that you have copied and pasted from different sources that use different methods of setting up controls.  Much of the code is unnecessary.  What you are trying to do can be done in less than half of the code.

Free Windows Admin Tool Kit Click here and download it now
September 1st, 2015 5:19am

A further look shows serious issues as you have not paid any attention to dependencies.  You are assigning values to objects that have not yet been created.  If you run this twice you will ne see the issues because the objects now exist but are not bound correctly to the form.

I recommend that you take some time to learn PowerShell before trying to build with forms.  Forms are difficult even for experienced programmers.  They can be nearly impossible for beginners.

You are dealing with an asynchronous, event driven programming model based on or targeted at objects.  THis is difficult to understand if you are not trained in modern technical programming.  You need to start small and try to understand how the form works before you can add code to it.  Learn that a form is complete and mostly independent without code.

In general all code in a form needs to be inn an event.  Of course this does not include the form/control creation code.  Events should have the least amount of code needed at that event level.  Most action code is placed in the "changed", "selected" or "checked" events for data controls and in the "click" for selection control like buttons.

September 1st, 2015 5:34am

You are trying to create a replacement for Explorer.  Why?  Explorer can multi-select files and also display checkboxes. 

If you are just trying to learn how to use PowerShell I recommend starting with a tutorial or a book because you do not have sufficient basic training to work on such sophisticated things you are trying to build with this form.  If you don't take the time to learn the fundamentals you will just become frustrated with PowerShell and forms.  Once you have the basics the rest is very easy and builds quickly.  Without the basics you will be in this same place a year from now.

To give you a start and some help with the "how" I have extracted the form building code and arranged it in a more sensible way.  I have not changed any of the positioning pieces.  As you will see it is badly broken.  Start by adjusting the location and size until you get it to display correctly. After that is done you can easily add events as needed.  The how-to will be very easy once the form is built correctly.

Free Windows Admin Tool Kit Click here and download it now
September 1st, 2015 6:09am

Here is a simple example form that does almost every thing that your form does and many more things. It is also an advanced display method which allows for themes and better display in newer Windows systems. It is very easy to use this in the ISE becase it has regions that can be collapsed making editing the code more reliable.

function Demo-ExplorerStyle{

	#----------------------------------------------
	#region Import the Assemblies
	#----------------------------------------------
	Add-Type -AssemblyName System.Windows.Forms
	#endregion Import Assemblies

	#----------------------------------------------

	#----------------------------------------------
	#region Form Objects
	#----------------------------------------------
	[System.Windows.Forms.Application]::EnableVisualStyles()
	$form1 = New-Object 'System.Windows.Forms.Form'
	$splitcontainer1 = New-Object 'System.Windows.Forms.SplitContainer'
	$buttonExit = New-Object 'System.Windows.Forms.Button'
	$listviewDetails = New-Object 'System.Windows.Forms.ListView'
	$treeviewNav = New-Object 'System.Windows.Forms.TreeView'
	$imagelistLargeImages = New-Object 'System.Windows.Forms.ImageList'
	$imagelistSmallImages = New-Object 'System.Windows.Forms.ImageList'
	$Name = New-Object 'System.Windows.Forms.ColumnHeader'
	$BaseName = New-Object 'System.Windows.Forms.ColumnHeader'
	$DirectoryName = New-Object 'System.Windows.Forms.ColumnHeader'
	$Length = New-Object 'System.Windows.Forms.ColumnHeader'
	$LastWriteTime = New-Object 'System.Windows.Forms.ColumnHeader'
	$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
	#endregion Generated Form Objects

	#----------------------------------------------
    #region Form init events

	$FormEvent_Load={
		#TODO: Initialize Form Controls here
		$treeviewNav.ExpandAll()
	}
	
	$treeviewNav_AfterSelect=[System.Windows.Forms.TreeViewEventHandler]{
	    #Event Argument: $_ = [System.Windows.Forms.TreeViewEventArgs]
	    $extension = $_.Node.Text
	    $listviewDetails.Items.Clear()
	    Get-ChildItem c:\scripts\*.* -Include "*.$extension" |
	        ForEach-Object{
	            $lvi=$listviewDetails.Items.add($_.Name)
	            $lvi.SubItems.Add($_.Basename)
	            $lvi.SubItems.Add($_.Length)
	            $lvi.SubItems.Add($_.LastWriteTime.ToString())
	            $lvi.SubItems.Add($_.DirectoryName)
		    }
	}
	
	$listviewDetails_SelectedIndexChanged={
	    if($listviewDetails.SelectedItems[0].Text){
	        [void][System.Windows.Forms.MessageBox]::Show($listviewDetails.SelectedItems[0].Text)
		}
	}
	#endregion Form init events

	#----------------------------------------------


	#------------------ ----------------------------
	#region Events
	#----------------------------------------------
	
	$Form_StateCorrection_Load=
	{
		#Correct the initial state of the form to prevent the .Net maximized form issue
		$form1.WindowState = $InitialFormWindowState
	}
	
	#endregion Generated Events

	#----------------------------------------------
	#region Generated Form Code
	#----------------------------------------------
	$form1.SuspendLayout()
	$splitcontainer1.SuspendLayout()
	#
	# form1
	#
	$form1.Controls.Add($splitcontainer1)
	$form1.Controls.Add($buttonExit)
	$form1.ClientSize = '1171, 607'
	$form1.Name = "form1"
	$form1.StartPosition = 'CenterScreen'
	$form1.Text = "Form"
	$form1.add_Load($FormEvent_Load)
	#
	# splitcontainer1
	#
	$splitcontainer1.Anchor = 'Top, Bottom, Left, Right'
	$splitcontainer1.Location = '12, 12'
	$splitcontainer1.Name = "splitcontainer1"
	[void]$splitcontainer1.Panel1.Controls.Add($treeviewNav)
	[void]$splitcontainer1.Panel2.Controls.Add($listviewDetails)
	$splitcontainer1.Size = '1147, 556'
	$splitcontainer1.SplitterDistance = 370
	$splitcontainer1.TabIndex = 3
	#
	# buttonExit
	#
	$buttonExit.DialogResult = 'Cancel'
	$buttonExit.Location = '553, 359'
	$buttonExit.Name = "buttonExit"
	$buttonExit.Size = '75, 23'
	$buttonExit.TabIndex = 2
	$buttonExit.Text = "E&xit"
	$buttonExit.UseVisualStyleBackColor = $True
	#
	# listviewDetails
	#
	$listviewDetails.Activation = 'TwoClick'
	[void]$listviewDetails.Columns.Add($Name)
	[void]$listviewDetails.Columns.Add($BaseName)
	[void]$listviewDetails.Columns.Add($Length)
	[void]$listviewDetails.Columns.Add($LastWriteTime)
	[void]$listviewDetails.Columns.Add($DirectoryName)
	$listviewDetails.Dock = 'Fill'
	$listviewDetails.FullRowSelect = $True
	$listviewDetails.GridLines = $True
	$listviewDetails.LabelWrap = $False
	$listviewDetails.LargeImageList = $imagelistLargeImages
	$listviewDetails.Location = '0, 0'
	$listviewDetails.MultiSelect = $False
	$listviewDetails.Name = "listviewDetails"
	$listviewDetails.Size = '773, 556'
	$listviewDetails.SmallImageList = $imagelistLargeImages
	$listviewDetails.TabIndex = 1
	$listviewDetails.UseCompatibleStateImageBehavior = $False
	$listviewDetails.View = 'Details'
	$listviewDetails.add_SelectedIndexChanged($listviewDetails_SelectedIndexChanged)
	#
	# treeviewNav
	#
	$treeviewNav.Dock = 'Fill'
	$treeviewNav.Location = '0, 0'
	$treeviewNav.Name = "treeviewNav"
	$System_Windows_Forms_TreeNode_2 = New-Object 'System.Windows.Forms.TreeNode' ("TXT")
	$System_Windows_Forms_TreeNode_2.Name = "TXT"
	$System_Windows_Forms_TreeNode_2.Text = "TXT"
	$System_Windows_Forms_TreeNode_3 = New-Object 'System.Windows.Forms.TreeNode' ("PS1")
	$System_Windows_Forms_TreeNode_3.Name = "PS1"
	$System_Windows_Forms_TreeNode_3.Text = "PS1"
	$System_Windows_Forms_TreeNode_4 = New-Object 'System.Windows.Forms.TreeNode' ("VBS")
	$System_Windows_Forms_TreeNode_4.Name = "VBS"
	$System_Windows_Forms_TreeNode_4.Text = "VBS"
	$System_Windows_Forms_TreeNode_5 = New-Object 'System.Windows.Forms.TreeNode' ("BAT")
	$System_Windows_Forms_TreeNode_5.Name = "BAT"
	$System_Windows_Forms_TreeNode_5.Text = "BAT"
	$System_Windows_Forms_TreeNode_1 = New-Object 'System.Windows.Forms.TreeNode' ("Extensions", [System.Windows.Forms.TreeNode[]] ($System_Windows_Forms_TreeNode_2, $System_Windows_Forms_TreeNode_3, $System_Windows_Forms_TreeNode_4, $System_Windows_Forms_TreeNode_5))
	$System_Windows_Forms_TreeNode_1.Name = "Extensions"
	$System_Windows_Forms_TreeNode_1.Text = "Extensions"
	[void]$treeviewNav.Nodes.Add($System_Windows_Forms_TreeNode_1)
	$treeviewNav.Size = '370, 556'
	$treeviewNav.TabIndex = 0
	$treeviewNav.add_AfterSelect($treeviewNav_AfterSelect)
	#
	# imagelistLargeImages
	#
	$imagelistLargeImages.ColorDepth = 'Depth32Bit'
	$imagelistLargeImages.ImageSize = '32, 32'
	$imagelistLargeImages.TransparentColor = 'Transparent'
	#
	# imagelistSmallImages
	#
	$imagelistSmallImages.ColorDepth = 'Depth32Bit'
	$imagelistSmallImages.ImageSize = '16, 16'
	$imagelistSmallImages.TransparentColor = 'Transparent'
	#
	# Name
	#
	$Name.Text = "Name"
	$Name.Width = 104
	#
	# BaseName
	#
	$BaseName.Text = "BaseName"
	$BaseName.Width = 116
	#
	# DirectoryName
	#
	$DirectoryName.Text = "DirectoryName"
	$DirectoryName.Width = 354
	#
	# Length
	#
	$Length.Text = "Length"
	$Length.TextAlign = 'Right'
	$Length.Width = 50
	#
	# LastWriteTime
	#
	$LastWriteTime.Text = "LastWriteTime"
	$LastWriteTime.Width = 143
	$splitcontainer1.ResumeLayout()
	$form1.ResumeLayout()
	#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($Form_StateCorrection_Load)
	#Show the Form
	return $form1.ShowDialog()

} #End Function

Demo-ExplorerStyle

Notice how clean the layout is and how it is easy to read.  Load it into the ISE and run it.  Run the debugger and step through the action code.  Once you understand how this works you will find it easier to build your own forms.  All forms should use a layout similar to this one.  Think about why things are placed as they are.  What is the advantage?  Why does the code require this ordering of things?

The original of this code was auto-generated by an IDE that builds PowerShell forms.  It is very predictable.  I have hand recoded this to make it easier to understand.  Before the IDE this pretty much how I hand coded forms using notepad.  Now you have the ISE to help with this.

September 1st, 2015 6:26am

Thanks for your reply!.. I will Reform the code and paste here
Free Windows Admin Tool Kit Click here and download it now
September 2nd, 2015 2:52am

Thanks for your suggestion! I will concentrate on Forms creation in powershell..

September 2nd, 2015 2:54am

The requirement is, we have to connect the remote machine(Computer) and get the temp files in the C: drive, Then we have to select and delete the files.

Finaly, send mail to server(computer) owner.

Thanks for your suggestion! I will concentrate on Forms creation in powershell..

Then I will Reform the code and paste here

Free Windows Admin Tool Kit Click here and download it now
September 2nd, 2015 6:46am

The requirement is, we have to connect the remote machine(Computer) and get the temp files in the C: drive, Then we have to select and delete the files.

Finaly, send mail to server(computer) owner.

Thanks for your suggestion! I will concentrate on Forms creation in powershell..

Then I will Reform the code and paste here

September 2nd, 2015 6:46am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics