List AD groups, create a CSV - powershell

I try to create a form which ask the share name, search depth and output filename and create a CSV file (which will require further processing, but this is not important now).
I have the graphical design and the script, but I cannot merge them to actually work together.
Here is the code:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Folder Group Details v1.6"
$Form.Size = New-Object System.Drawing.Size(700,400)
$Form.StartPosition = "Manual"
$Form.Location = New-Object System.Drawing.Size(90,90)
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Font = New-Object System.Drawing.Font("Times New Roman",14,[System.Drawing.FontStyle]::Bold)
$Form.Width = $objImage.Width
$Form.Height = $objImage.Height
# Title
$Title = New-Object System.Windows.Forms.label
$Title.Location = New-Object System.Drawing.Size(150,10)
$Title.Size = New-Object System.Drawing.Size(500,70)
$Title.BackColor = "Transparent"
$Title.ForeColor = "darkblue"
$Title.Text = "Create a CSV file for the given path and depth"
$Form.Controls.Add($Title)
$Title.Font = $Font
# Start button
$Start_Button = New-Object System.Windows.Forms.Button
$Start_Button.Location = New-Object System.Drawing.Size(50,300)
$Start_Button.Size = New-Object System.Drawing.Size(100,30)
$Start_Button.Text = "Start"
$Start_Button.Font = $Font
$Start_Button.Add_Click($Button_Click)
$Form.Controls.Add($Start_Button)
#Cancel button
$Cancel_Button = New-Object System.Windows.Forms.Button
$Cancel_Button.Location = New-Object System.Drawing.Size(550,300)
$Cancel_Button.Size = New-Object System.Drawing.Size(100,30)
$Cancel_Button.Text = "Cancel"
$Cancel_Button.Font = $Font
$Cancel_Button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.Controls.Add($Cancel_Button)
$arg0_label = New-Object System.Windows.Forms.Label
$arg0_label.Location = New-Object System.Drawing.Point(50,80)
$arg0_label.Size = New-Object System.Drawing.Size(280,20)
$arg0_label.Text = 'Please enter the root of path:'
$Form.Controls.Add($arg0_label)
$arg0_textBox = New-Object System.Windows.Forms.TextBox
$arg0_textBox.Location = New-Object System.Drawing.Point(80,100)
$arg0_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg0_textBox.Multiline = $False
$arg0_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg0_textBox)
$arg2_label = New-Object System.Windows.Forms.Label
$arg2_label.Location = New-Object System.Drawing.Point(50,130)
$arg2_label.Size = New-Object System.Drawing.Size(280,20)
$arg2_label.Text = 'Please enter the depth of search:'
$Form.Controls.Add($arg2_label)
$arg2_textBox = New-Object System.Windows.Forms.TextBox
$arg2_textBox.Location = New-Object System.Drawing.Point(80,150)
$arg2_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg2_textBox.Multiline = $False
$arg2_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg2_textBox)
$arg1_label = New-Object System.Windows.Forms.Label
$arg1_label.Location = New-Object System.Drawing.Point(50,180)
$arg1_label.Size = New-Object System.Drawing.Size(280,20)
$arg1_label.Text = 'Please enter the output file full path and name:'
$Form.Controls.Add($arg1_label)
$arg1_textBox = New-Object System.Windows.Forms.TextBox
$arg1_textBox.Location = New-Object System.Drawing.Point(80,200)
$arg1_textBox.Size = New-Object System.Drawing.Size(250,30)
$arg1_textBox.Multiline = $False
$arg1_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg1_textBox)
#$outfile = "$arg1_textBox.Text"
# Button event
$Button_Click = {
$RootPath = $arg0_textBox.Text
$OutFile = $arg1_textBox.Text
$recurse_max = $arg2_textBox.Text
$recurse_current = 0
$Header = "Folder Path,IdentityReference,FileSystemRights,IsInherited"
Remove-Item $OutFile
Add-Content -Value $Header -Path $OutFile
function print_acl
{
$RootPath = $arg0_textBox.Text
$recurse_current = $arg1_textBox.Text
Write-Host "$RootPath : $recurse_current"
if ($RootPath -ne "" -and $null -ne $RootPath ) {
$ACLs = get-acl $RootPath | ForEach-Object { $_.Access }
Foreach ($ACL in $ACLs){
$rights = $ACL.FileSystemRights -replace ", ", ":"
$OutInfo = $RootPath + "," + $ACL.IdentityReference + "," + $rights + "," + $ACL.IsInherited
Add-Content -Value $OutInfo -Path $OutFile
}
if ($recurse_current -lt $recurse_max) {
$Folders = Get-ChildItem $RootPath | Where-Object {$_.psiscontainer -eq $true}
foreach ($Folder in $Folders){
$recurse_current = $arg1_textBox.Text + 1
print_acl $Folder.Fullname $recurse_current
}
}
}
}
print_acl $RootPath $recurse_current
}
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
The problem is I don't understand why the Start button don't do anything.
What do I do wrong?
I'm a very beginner in this field so sorry for being so lame.
Thank you.

There's no need to make your own recursive function for Get-ChildItem - it has a -Depth Parameter
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Folder Group Details v1.6"
$Form.Size = '700,400'
$Form.StartPosition = "Manual"
$Form.Location = '90,90'
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Font = New-Object System.Drawing.Font("Times New Roman",14,[System.Drawing.FontStyle]::Bold)
$Form.Width = $objImage.Width
$Form.Height = $objImage.Height
# Title
$Title = New-Object System.Windows.Forms.label
$Title.Location = '150,10'
$Title.Size = '500,70'
$Title.BackColor = "Transparent"
$Title.ForeColor = "darkblue"
$Title.Text = "Create a CSV file for the given path and depth"
$Form.Controls.Add($Title)
$Title.Font = $Font
# Start button
$Start_Button = New-Object System.Windows.Forms.Button
$Start_Button.Location = '50,300'
$Start_Button.Size = '100,30'
$Start_Button.Text = "Start"
$Start_Button.Font = $Font
$Start_Button.Add_Click($Button_Click)
$Form.Controls.Add($Start_Button)
#Cancel button
$Cancel_Button = New-Object System.Windows.Forms.Button
$Cancel_Button.Location = '550,300'
$Cancel_Button.Size = '100,30'
$Cancel_Button.Text = "Cancel"
$Cancel_Button.Font = $Font
$Cancel_Button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$Form.Controls.Add($Cancel_Button)
$arg0_label = New-Object System.Windows.Forms.Label
$arg0_label.Location = '50,80'
$arg0_label.Size = '280,20'
$arg0_label.Text = 'Please enter the root of path:'
$Form.Controls.Add($arg0_label)
$arg0_textBox = New-Object System.Windows.Forms.TextBox
$arg0_textBox.Location = '80,100'
$arg0_textBox.Size = '250,30'
$arg0_textBox.Multiline = $False
$arg0_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg0_textBox)
$arg2_label = New-Object System.Windows.Forms.Label
$arg2_label.Location = '50,130'
$arg2_label.Size = '280,20'
$arg2_label.Text = 'Please enter the depth of search:'
$Form.Controls.Add($arg2_label)
$arg2_textBox = New-Object System.Windows.Forms.TextBox
$arg2_textBox.Location = '80,150'
$arg2_textBox.Size = '250,30'
$arg2_textBox.Multiline = $False
$arg2_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg2_textBox)
$arg1_label = New-Object System.Windows.Forms.Label
$arg1_label.Location = '50,180'
$arg1_label.Size = '280,20'
$arg1_label.Text = 'Please enter the output file full path and name:'
$Form.Controls.Add($arg1_label)
$arg1_textBox = New-Object System.Windows.Forms.TextBox
$arg1_textBox.Location = '80,200'
$arg1_textBox.Size = '250,30'
$arg1_textBox.Multiline = $False
$arg1_textbox.AcceptsReturn = $False
$Form.Controls.Add($arg1_textBox)
# Button event
$Button_Click = {
$RootPath = $arg0_textBox.Text
$OutFile = $arg1_textBox.Text
$recurse_max = $arg2_textBox.Text
$Results = Get-ChildItem -Path $RootPath -Depth $recurse_max | Where-Object {$_.psiscontainer -eq $true} | ForEach-Object {
$FileDetail = $_
$ACLs = get-acl $_.FullName | ForEach-Object { $_.Access }
$ACLs | ForEach-Object {
$rights = $_.FileSystemRights -replace ", ", ":"
[pscustomobject]#{Folder=$FileDetail.Name;Path=$FileDetail.FullName;IdentityReference=$_.IdentityReference;FileSystemRights=$rights;IsInherited=$_.IsInherited}
}
}
$Results | Export-Csv -Path $OutFile -NoTypeInformation
}
$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

Related

How to remove checked margin in tray icon context menu

I've created this little script running in tray. I've noticed that contex menu text is not placed completely to the left. After a little investigation I found out that it is because there is a space left for .checked state indicator. I found out that it can be removed by .showcheckedmargin property of ContextMenuStrip but have no idea how to implement that.
Please advise.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$2 = "BASE64 CODE"
$bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap.BeginInit()
$bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($2)
$bitmap.EndInit()
$bitmap.Freeze()
$image = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap.StreamSource)
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app = New-Object System.Windows.Forms.NotifyIcon
$app.Text = ""
$app.Icon = $icon
$app.Visible = $true
$Zenek = New-Object System.Windows.Forms.MenuItem
$Zenek.Text = "Zenek"
$NetExt = New-Object System.Windows.Forms.MenuItem
$NetExt.Text = "NetExt"
$Busy = New-Object System.Windows.Forms.MenuItem
$Busy.Text = "BUSY"
$Time = New-Object System.Windows.Forms.MenuItem
$Time.Text = "Time"
$Exit = New-object System.Windows.Forms.MenuItem
$Exit.Text = "Exit"
$context = New-Object System.Windows.Forms.ContextMenu
$app.ContextMenu = $context
$app.ContextMenu.MenuItems.AddRange(#($Zenek, $NetExt, $Busy, $Time, $Exit))
$keepAwakeScript = {
while (1) {
$wsh = New-Object -ComObject WScript.Shell
$wsh.SendKeys('+{F15}')
Start-Sleep -seconds 59
}
}
Start-Job -ScriptBlock $keepAwakeScript -Name "keepAwake"|out-null
$Zenek.Add_Click({Set-Clipboard -Value "SOME TEXT"})
$NetExt.Add_Click({Set-Clipboard -Value "SOME OTHER TEXT"})
$Busy.Add_Click({
$running = Get-Job|?{$_.Name -like 'KAPS'}
$icon = new-object System.Drawing.Icon("MY PRIVATE LOCATION\red.ico")
$app.Icon = $icon
if($running -eq $null){
Start-Job -Name KAPS -ScriptBlock{
while ($true){
$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys('{CAPSLOCK}')
Start-Sleep 1
}
}
}else{
Stop-Job KAPS
Remove-Job KAPS
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app.Icon = $icon
}
})
$Time.Add_Click({
$main = New-Object System.Windows.Forms.Form
$main.ClientSize = '200,200'
$main.MinimizeBox = $false
$main.MaximizeBox = $false
$label = New-Object System.Windows.Forms.Label
$label.Size = '190,30'
$label.Location = '10,10'
$label.Text = 'Ile minut?'
$font = New-Object System.Drawing.Font("Arial", 23)
$label.Font = $font
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Size = '50,100'
$textbox.Location = '10,70'
$button = New-Object System.Windows.Forms.Button
$button.Size = '50,50'
$button.Location = '10,120'
$button.Text = 'GO'
$button.Add_Click({
$timer.Start()
$textbox.Visible =$false
$button.Visible = $false
$label.Visible = $false
$script:1 = New-TimeSpan -minutes ([int]$textbox.Text)
$label2.Visible = $true
$label2.Text = $1.ToString("mm\:ss")
})
$timer = New-Object System.Windows.Forms.Timer
$timer.Enabled = $false
$timer.Interval = '1000'
$second = New-TimeSpan -Seconds 1
$timer.Add_Tick({
$script:1 = $1.Subtract($second)
$label2.Text = $1.ToString("mm\:ss")
if($script:1.TotalSeconds -le 0){$timer.Stop(); $timer.Dispose(); [System.Windows.Forms.Application]::SetSuspendState("Hibernate", $true, $false); $main.Close(); $main.Dispose()}
})
$label2 = New-Object System.Windows.Forms.Label
$label2.Size = '190,30'
$label2.Location = '10,10'
$label2.Text = $1
$font = New-Object System.Drawing.Font("Arial", 23)
$label2.Font = $font
$label2.Visible = $false
$main.Controls.Add($textbox)
$main.Controls.Add($button)
$main.Controls.Add($label)
$main.Controls.Add($label2)
$main.ShowDialog()
})
$Exit.Add_Click({
$app.Visible = $false
Stop-Job -Name "keepAwake"
$appContext.ExitThread()
Stop-Process -Id $PID
})
$appContext = New-Object System.Windows.Forms.ApplicationContext
[void][System.Windows.Forms.Application]::Run($appContext)
For anyone with the same problem. I've managed to figure it out.
Another post from SO allowed me to do so.
I had to replace .ContextMenu with .ContextMenuStrip for the Menu itself,
replace .MenuItem with .ToolStripMenuItem, add .ShowImageMargin to ContextMenuStrip variable, then finall add items via .Items.AddRange(#()).
Before
After
In the end the code looks like this and works as intended.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$2 =
"BASE 64 CODE"
$bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap.BeginInit()
$bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($2)
$bitmap.EndInit()
$bitmap.Freeze()
$image = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap.StreamSource)
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app = New-Object System.Windows.Forms.NotifyIcon
$app.Text = ""
$app.Icon = $icon
$app.Visible = $true
$Zenek = New-Object System.Windows.Forms.ToolStripMenuItem
$Zenek.Text = "Zenek"
$Zenek.Checked = $true
$NetExt = New-Object System.Windows.Forms.ToolStripMenuItem
$NetExt.Text = "NetExt"
$Busy = New-Object System.Windows.Forms.ToolStripMenuItem
$Busy.Text = "BUSY"
$Time = New-Object System.Windows.Forms.ToolStripMenuItem
$Time.Text = "Time"
$Exit = New-object System.Windows.Forms.ToolStripMenuItem
$Exit.Text = "Exit"
$sep = New-Object System.Windows.Forms.ToolStripSeparator
$context = New-Object System.Windows.Forms.ContextMenuStrip
$context.ShowImageMargin = $false
$context.Items.AddRange(#($Zenek, $NetExt, $Busy, $Time, $sep, $Exit))
$app.ContextMenuStrip = $context
$keepAwakeScript = {
while (1) {
$wsh = New-Object -ComObject WScript.Shell
$wsh.SendKeys('+{F15}')
Start-Sleep -seconds 59
}
}
Start-Job -ScriptBlock $keepAwakeScript -Name "keepAwake"|out-null
$Zenek.Add_Click({Set-Clipboard -Value "SOME TEXT"})
$NetExt.Add_Click({Set-Clipboard -Value "SOME OTHER TEXT"})
$Busy.Add_Click({
$running = Get-Job|?{$_.Name -like 'KAPS'}
$icon = new-object System.Drawing.Icon("MY PRIVATE LOCATION\red.ico")
$app.Icon = $icon
if($running -eq $null){
Start-Job -Name KAPS -ScriptBlock{
while ($true){
$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys('{CAPSLOCK}')
Start-Sleep 1
}
}
}else{
Stop-Job KAPS
Remove-Job KAPS
$icon = [System.Drawing.Icon]::FromHandle($image.GetHicon())
$app.Icon = $icon
}
})
$Time.Add_Click({
$main = New-Object System.Windows.Forms.Form
$main.ClientSize = '200,200'
$main.MinimizeBox = $false
$main.MaximizeBox = $false
$label = New-Object System.Windows.Forms.Label
$label.Size = '190,30'
$label.Location = '10,10'
$label.Text = 'Ile minut?'
$font = New-Object System.Drawing.Font("Arial", 23)
$label.Font = $font
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Size = '50,100'
$textbox.Location = '10,70'
$button = New-Object System.Windows.Forms.Button
$button.Size = '50,50'
$button.Location = '10,120'
$button.Text = 'GO'
$button.Add_Click({
$timer.Start()
$textbox.Visible =$false
$button.Visible = $false
$label.Visible = $false
$script:1 = New-TimeSpan -minutes ([int]$textbox.Text)
$label2.Visible = $true
$label2.Text = $1.ToString("mm\:ss")
})
$timer = New-Object System.Windows.Forms.Timer
$timer.Enabled = $false
$timer.Interval = '1000'
$second = New-TimeSpan -Seconds 1
$timer.Add_Tick({
$script:1 = $1.Subtract($second)
$label2.Text = $1.ToString("mm\:ss")
if($script:1.TotalSeconds -le 0){$timer.Stop(); $timer.Dispose(); [System.Windows.Forms.Application]::SetSuspendState("Hibernate", $true, $false); $main.Close(); $main.Dispose()}
})
$label2 = New-Object System.Windows.Forms.Label
$label2.Size = '190,30'
$label2.Location = '10,10'
$label2.Text = $1
$font = New-Object System.Drawing.Font("Arial", 23)
$label2.Font = $font
$label2.Visible = $false
$main.Controls.Add($textbox)
$main.Controls.Add($button)
$main.Controls.Add($label)
$main.Controls.Add($label2)
$main.ShowDialog()
})
$Exit.Add_Click({
$app.Visible = $false
Stop-Job -Name "keepAwake"
$appContext.ExitThread()
#Stop-Process -Id $PID
})
$appContext = New-Object System.Windows.Forms.ApplicationContext
[void][System.Windows.Forms.Application]::Run($appContext)

Add an existing Progressbar into an GUI

I have writen an simple GUI for my command to display. When i press a button my script searches for matches in a Log File and while doing that it displays a Progressbar, but it only displays it in the ISE Window not in the GUI itself. How can i Display it in the GUI.
I found New-Object System.Windows.Forms.ProgressBar when searching for a way.
But in the examples i only found how they do new Bars not add existings that only exist inside of a Button.
This is my Script
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
#Dropdown/Serverauswahl
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select a Computer'
$form.Size = New-Object System.Drawing.Size(600,400)
$form.StartPosition = 'CenterScreen'
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(150,240)
$okButton.Size = New-Object System.Drawing.Size(150,46)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(300,240)
$cancelButton.Size = New-Object System.Drawing.Size(150,46)
$cancelButton.Text = 'Cancel'
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$form.Controls.Add($cancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(560,40)
$label.Text = 'Please select a Server:'
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(20,80)
$listBox.Size = New-Object System.Drawing.Size(540,40)
$listBox.Font = "courier New, 13"
$listBox.Height =150
[void] $listBox.Items.Add('LNS5')
[void] $listBox.Items.Add('LNS10')
[void] $listBox.Items.Add('LNS13')
[void] $listBox.Items.Add('LNS14')
[void] $listBox.Items.Add('LNS62')
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox.SelectedItem
$path = "C:\temp\SMTPFilter\${x}filter.txt"
}
#zweites Fenster
$objForm = New-Object System.Windows.Forms.Form
$objForm.StartPosition = "CenterScreen"
$objForm.Size = New-Object System.Drawing.Size(1200,800)
$objForm.Text = "Test GUI"
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(900,600)
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(800,400)
#Filtern
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,112)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Filtern"
$OKButton.Name = "Filter"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::None
$OKButton.Add_Click({$i= 0
$length = (Get-Content $path).Length
$global:result = Get-Content $path | ForEach-Object {
if($_ -match '(\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}).*\(((?:\d{1,3}\.){3}\d{1,3})\) disconnected\.?\s+(\d+) message\[s\]'){
[PsCustomObject]#{
IP = $matches[2]
Messages = [int]$matches[3]
Date = [datetime]::ParseExact($matches[1], 'dd.MM.yyyy HH:mm:ss', $null)
}}
$i++
if($i % 1000 -eq 0){
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
}}
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length) * 100)
#Messages Counted
$global:cumulative = $result | Group-Object -Property IP | ForEach-Object {
try {
$dns = [System.Net.Dns]::GetHostEntry($_.Name).HostName
}
catch {
$dns = 'Not available'
}
[PsCustomObject]#{
IP = $_.Name
Messages = ($_.Group | Measure-Object -Property Messages -Sum).Sum
DNSName = $dns
Date = ($_.Group | Sort-Object Date)[-1].Date
}
}})
$objForm.Controls.Add($OKButton)
#Ergebnis Anzeigen
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,214)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Ergebnis anzeigen"
$OKButton.Name = "Egebnis Button"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::None
$OKButton.Add_Click({$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Multiline = $True;
$objTextBox1.Location = New-Object System.Drawing.Size(360,10)
$objTextBox1.Size = New-Object System.Drawing.Size(800,600)
$objTextBox1.Text = $cumulative | Out-String
$objTextBox1.Font = "courier New, 13"
$objTextBox1.Scrollbars = "Vertical"
$objForm.Controls.Add($objTextBox1)
#outgridview
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,316)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Ergebnis in GridView"
$OKButton.Name = "GridView"
$OKButton.DialogResult = "OK"
$OKButton.Add_Click({$cumulative | Out-GridView})
$objForm.Controls.Add($OKButton)
#Export CSV
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,418)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Export CSV (in C:/temp)"
$OKButton.Name = "CSV"
$OKButton.DialogResult = "OK"
$OKButton.Add_Click({$cumulative | Export-Csv -Path 'C:\temp\SMTPresult.Csv'})
$objForm.Controls.Add($OKButton) })
$objForm.Controls.Add($OKButton)
[void] $objForm.ShowDialog()
There is a ProgressBar control available which you can use:
System.Windows.Forms.ProgressBar
See https://mcpmag.com/articles/2014/02/18/progress-bar-to-a-graphical-status-box.aspx for an example
There is also a way of displaying a progressbar inside the taskbar button but you need to deploy a dll from the Microsoft WindowsAPICodePack so that it's available to the person running the script. If you're interested I'll dig out the details

How to handle button to open a file using Powershell?

I want to open a file after I select the file using the GUI. When I try my code, I can not open the file I selected. It returns Get-Content Cannot find the path. Anyone can help me, please.
Function File ($InitialDirectory)
{
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.SafeFileName
Get-Content "$Global:SelectedFile" | ForEach-Object {
$_.Trim()
} | Where-Object {
$_ -notmatch '^(;|$)'
} | ForEach-Object {
if ($_ -match '^\[.*\]$') {
$section = $_ -replace '\[|\]'
$ini_file[$section] = #{}
} else {
$key, $value = $_ -split '\s*=\s*', 2
$ini_file[$section][$key] = $value
}
}
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Choose2.Add_Click({Sel_File
$Sel.Text = $Global:SelectedFile
})
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
My expectation, I can open the file because I want to process the file. The file that I want to open is .INI file.
Function File ($InitialDirectory)
{
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.FileName
}
Function Get-IniContent ($Global:SelectedFile)
{
$ini = #{}
switch -regex -file $Global:SelectedFile
{
“^\[(.+)\]” # Section
{
$section = $matches[1]
$ini[$section] = #{}
$CommentCount = 0
}
“^(;.*)$” # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = “Comment” + $CommentCount
$ini[$section][$name] = $value
}
“(.+?)\s*=(.*)” # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
$iniContent = Get-IniContent $Global:SelectedFile
$Region = $iniContent[“Location”]
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Choose2.Add_Click({File
$Sel.Text = $Global:SelectedFile
})
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
I use edited code, but I can not handle the button. I want to read the INI Section [Location] after I select the file. With this code, The section already printed before I select the file.
You don't need Global variables at all for this.. Basically, the main form should capture the $Sel.Text from the dialog into a variable, check if that is not the default value of "Selected" and that should do it:
function Select-File ($InitialDirectory) {
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
If ($OpenFileDialog.ShowDialog() -eq "Cancel") {
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
$result = $null
}
else {
$result = $OpenFileDialog.FileName
}
$OpenFileDialog.Dispose()
return $result
}
function Get-IniContent ($FilePath) {
$ini = #{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = #{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"(.+?)\s*=(.*)" # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
###############
# Main routine
###############
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "OpenFile"
$Form.TopMost = $true
#----------------------
$Choose1 = New-Object system.Windows.Forms.Label
$Choose1.text = "MLs"
$Choose1.AutoSize = $true
$Choose1.width = 25
$Choose1.height = 10
$Choose1.location = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor = "#000000"
$Sel = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize = $true
$Sel.width = 150
$Sel.height = 30
$Sel.location = New-Object System.Drawing.Point(120,40)
$Sel.Text = "Selected"
$Choose2 = New-Object System.Windows.Forms.Button
$Choose2.text = "Select File"
$Choose2.AutoSize = $true
$Choose2.width = 90
$Choose2.height = 20
$Choose2.location = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor = "#ffffff"
$Choose2.BackColor = "#093c76"
$Choose2.Add_Click({ $Sel.Text = Select-File })
$Close = New-Object system.Windows.Forms.Button
$Close.BackColor = "#6996c8"
$Close.text = "Close"
$Close.width = 98
$Close.height = 30
$Close.location = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------
$Form.Controls.AddRange(#($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()
# if the user did not fill in anything and left the default text of "Selected", set the result to null
$selectedFile = if ($Sel.Text -ne "Selected") { $Sel.Text } else { $null }
# clean up the form
$Form.Dispose()
# here, we test if there is a file selected and if it exists
if ($selectedFile -and (Test-Path -Path $selectedFile -PathType Leaf)) {
Write-Host "Reading INI file '$($selectedFile)'"
$iniContent = Get-IniContent $selectedFile
$Region = $iniContent["Location"]
$region
}
else {
Write-Warning "The dialog was cancelled or the selected file cannot be found."
}
As per my comment, you need to change the $OpenFileDialog.SafeFileName to $OpenFileDialog.FileName.
# SafeFileName = "Config.ini"
# FileName = "\\UNC\Path\Config.ini" or "C:\Temp\Config.ini"
Function File ($InitialDirectory) {
Add-Type -AssemblyName System.Windows.Forms
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.FileName
Get-Content "$Global:SelectedFile" | ForEach-Object {
$_.Trim()
} | Where-Object {
$_ -notmatch '^(;|$)'
} | ForEach-Object {
if ($_ -match '^\[.*\]$') {
$section = $_ -replace '\[|\]'
$ini_file[$section] = #{}
} else {
$key, $value = $_ -split '\s*=\s*', 2
$ini_file[$section][$key] = $value
}
}
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

Powershell Switchcase for CSV Filtering-> Process runtrough ->and Ouput

I would like to be able to select which csv runs through as the input csv's are standardiesd and i need to filter for the process. My problem is i cant handle the Filter part. The Process is running fine i tested it several times. Also the csv load is working and the save at part as well those got tested seperatly as well. But as soon as the switchcase and the filter part are in it doesnt work anymore. But i need it as otherwise i have to write 3 more scripts what wouldnt make sense. Any recommandtion how to pass this filter.
Full Code
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#Select which option and which CSV
$form = New-Object System.Windows.Forms.Form
$form.Text = "CSV Liste"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,195)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,195)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Welche CSV Liste soll geladen werden:"
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 150
[void] $listBox.Items.Add("AS400 Computer")
[void] $listBox.Items.Add("AS400 Personalstamm")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("ADBenutzer")
$form.Controls.Add($listBox)
$form.Topmost = $True
$result = $form.ShowDialog()
#Filter for the CSV
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.initialDirectory = $initialDirectory
$location.filter = "CSV (*.csv)| *.csv"
$location.ShowDialog()
$CSV = Import-Csv -Path $location.FileName -UseCulture
$x = $listBox.SelectedItem
switch ($x)
{
"AS400 Computer"
{
$y = $CSV | Select Inventarnummer
}
"AS400 Personalstamm"
{
$y = $CSV | Select filter1
}
"ADComputer"
{
$y = $CSV | Select filter1
}
"ADBenutzer"
{
$y = $CSV | Select filter1
}
}
}
#Save Data at
$Saveworking = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveworking.filter = "CSV (*.csv)| *.csv"
$Saveworking.ShowDialog()
$Savefailed = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Savefailed.filter = "CSV (*.csv)| *.csv"
$Savefailed.ShowDialog()
#Process Runtrough
foreach($n in $y)
{
try {
$Computer = [system.net.dns]::resolve($n.NAME) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.NAME $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.NAME} | Export-Csv $Saveworking.FileName -NoTypeInformation -Append
} catch {
Write-Host "$($n.NAME) is unreachable."
New-Object PSObject -Property #{Name=$n.NAME} | Export-Csv $Savefailed.FileName -NoTypeInformation -Append
}
}
edit: Code updated can now select Column and is working allmost. As it seems it cant run the Process right now as it is not felxible enough. Working on Solution appricate any recommandtions.

change the dates in two place in a text

Looking to change yyyy,MM,dd to user input date. Similarly looking to change abcd,ef,gh also to user input date. abcd,ef,gh gets succesfully converted to the date user inputs. However, yyyy,MM,dd stays the same.
Here is the data in the output text file:
(Global History"&customer=guest&password=guest&STARTTIME=yyyy,MM,dd,00,00,00&STOPTIME=abcd,ef,gh,00,00,00&POINTSEVERY=15 min&GRAPHTYPE=excel)
Here is the script:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object Windows.Forms.Form
$form.Text = "Select a From Date"
$form.Size = New-Object Drawing.Size #(243,230)
$form.StartPosition = "CenterScreen"
$calendar = New-Object System.Windows.Forms.MonthCalendar
$calendar.ShowTodayCircle = $False
$calendar.MaxSelectionCount = 1
$form.Controls.Add($calendar)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(38,165)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(113,165)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$form.Topmost = $True
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
Remove-Item H:\oim\adcbsm007\karthik.txt
$path = "H:\oim\adcbsm007\adcbsm007.txt"
$word1 = "yyyy,MM,dd"
$replacement = $calendar.SelectionStart
$text1 = Get-Content $path
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
$newText > "H:\oim\adcbsm007\karthik.txt"
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$path = "H:\oim\adcbsm007\adcbsm007.txt"
$word = "abcd,ef,gh"
$replacement2 = $calendar.SelectionStart
$text = Get-Content $path
$newText = $text2 -replace $word, $replacement.ToString('yyyy,MM,dd')
$newText > "H:\oim\adcbsm007\karthik.txt"
}
}
You initialize the variables $word1 and $text1, but then you try to replace $word in $text:
$word1 = "yyyy,MM,dd"
$replacement = $calendar.SelectionStart
$text1 = Get-Content $path
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
Replace the line
$newText = $text -replace $word, $replacement.ToString('yyyy,MM,dd')
with
$newText = $text1 -replace $word1, $replacement.ToString('yyyy,MM,dd')
and the code should do what you expect.