If is not working in If-elseif statement - forms

Im writing a code which asks the user to mark certain files that he wants and then it creates a file and changes it accordingly, just wrote hello for now.
The problem is that it only works in the if section, and not in the else if. I couldn't find an answer online.
Here is my code:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName ("System.Windows.Forms")
#This creates the path for the Json
New-Item c:\users\$env:USERNAME\documents -ItemType directory -Name Json
#creating the form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Ofir`s script"
$objForm.Size = New-Object System.Drawing.Size(270,200)
$objForm.StartPosition = "CenterScreen"
#creating the label
$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 check the relevant boxes:"
$objForm.Controls.Add($objLabel)
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(10,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates a checkbox called fpga.bin
$objFpgaCheckbox = New-Object System.Windows.Forms.Checkbox
$objFpgaCheckbox.Location = New-Object System.Drawing.Size(10,60)
$objFpgaCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objFpgaCheckbox.Text = "fpga.bin"
$objFpgaCheckbox.TabIndex = 1
$objForm.Controls.Add($objFpgaCheckbox)
#This creates a checkbox called bootrom_uncmp.bin
$objBootCheckbox = New-Object System.Windows.Forms.Checkbox
$objBootCheckbox.Location = New-Object System.Drawing.Size(10,80)
$objBootCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objBootCheckbox.Text = "bootrom_uncmp.bin"
$objBootCheckbox.TabIndex = 2
$objForm.Controls.Add($objBootCheckbox)
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(40,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({if ($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()}
}
)
elseif ($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif ($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
$objForm.Controls.Add($OKButton)
#cancle Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(140,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
#makes the form appear on top of the screen
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

You have a curly-bracket in this line:
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()}
So change the click handler to:
$OKButton.Add_Click(
{
if ($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()
}
elseif ($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif ($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
})

This is working fine now with the elseif . I have made few improvements like if the json folder is already existing then it was throwing error . So I am checking on prior that if the folder is already there then do not create or overwrite. Use that same folder and create the Json file under that. If the folder is not present then only create it.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
#This creates the path for the Json and also check if it is already there.
If(!(Test-Path -Path C:\Users\$env:USERNAME\documents\Json))
{
New-Item c:\users\$env:USERNAME\documents -ItemType directory -Name Json
}
#creating the form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Ofir`s script"
$objForm.Size = New-Object System.Drawing.Size(270,200)
$objForm.StartPosition = "CenterScreen"
#creating the label
$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 check the relevant boxes:"
$objForm.Controls.Add($objLabel)
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(10,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates a checkbox called fpga.bin
$objFpgaCheckbox = New-Object System.Windows.Forms.Checkbox
$objFpgaCheckbox.Location = New-Object System.Drawing.Size(10,60)
$objFpgaCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objFpgaCheckbox.Text = "fpga.bin"
$objFpgaCheckbox.TabIndex = 1
$objForm.Controls.Add($objFpgaCheckbox)
#This creates a checkbox called bootrom_uncmp.bin
$objBootCheckbox = New-Object System.Windows.Forms.Checkbox
$objBootCheckbox.Location = New-Object System.Drawing.Size(10,80)
$objBootCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objBootCheckbox.Text = "bootrom_uncmp.bin"
$objBootCheckbox.TabIndex = 2
$objForm.Controls.Add($objBootCheckbox)
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(40,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click(
{
if($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()
}
elseif($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
}
)
$objForm.Controls.Add($OKButton)
#cancle Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(140,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
#makes the form appear on top of the screen
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

Related

copy file in a gui with checkboxes

i'm creating a gui in powershell for copying files. first i add a file with a button, next i choose the folder where to copy and then i want to copy. unfortunately the script says the file path is empty. how can i solve this problem? Furthermore, i want to add 2 functions.
a warning if no checkbox is marked
a text field next to the choose button where i can see the path from the file i want to copy
$PSDefaultParameterValues['*:Encoding'] = 'ascii'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#create form
$form = New-Object System.Windows.Forms.Form
$form.Width = 500
$form.Height = 300
$form.MaximizeBox = $false
#choose file button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(10,10)
$Button.Size = New-Object System.Drawing.Size(150,50)
$Button.Text = "choose file"
$Button.Add_Click({
Function Get-FileName($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$file = Get-FileName -initialDirectory “c:”
})
$form.Controls.Add($Button)
#create checkbox1
$checkBox = New-Object System.Windows.Forms.CheckBox
$checkBox.Location = New-Object System.Drawing.Point (10, 100)
$checkBox.Size = New-Object System.Drawing.Size(350,30)
$checkBox.Text = "folder 1"
$form.Controls.Add($checkBox)
#create checkbox2
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox2.Location = New-Object System.Drawing.Point (10, 150)
$checkBox2.Size = New-Object System.Drawing.Size(350,30)
$checkBox2.Text = "folder 2"
$form.Controls.Add($checkBox2)
#copy file button
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Size(10,200)
$Button2.Size = New-Object System.Drawing.Size(150,50)
$Button2.Text = "copy file"
$Button2.Add_Click({
#checkbox1 action
if ($checkBox.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 1"
}
#checkbox2 action
if ($checkBox2.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 2"
}
})
$form.Controls.Add($Button2)
#end
[void]$form.ShowDialog()
There are plenty of improvements to be suggested but let's focus on your questions:
The problem is that the scope of your $file variable is local to the function Get-Filename.
So when accessed from outside of the function, it is always null.
As stated in the comments, the minimum modification for your script to work is the change the following line (I would also suggest to declare it initially outside of the function, at global level for sake of clarity):
# From this
$file = Get-FileName -initialDirectory "c:"
# To this
$Global:file = Get-FileName -initialDirectory "c:"
To add a textbox with the choosen filename, proceed as for the other controls:
#Text box with choosen file name
$txtBox = New-Object System.Windows.Forms.TextBox
$txtBox.Location = New-Object System.Drawing.Point (180, 20)
$txtBox.Size = New-Object System.Drawing.Size(280,20)
$form.Controls.Add($txtBox)
And to update the text, add the following line after setting the $Global:file variable:
$Global:file = Get-FileName -initialDirectory "c:"
$txtBox.Text = $Global:file
Finally, a message can be displayed if you add the following code to your $Button2.Add_Click code:
#nothing checked
if(($checkBox.Checked -eq $false) -and ($checkBox.Checked -eq $false)) {
[System.Windows.Forms.Messagebox]::Show("No CheckBox checked")
}

powershell gui creating local users

i need some help with my powershell gui. i want to create a gui for creating local useraccounts with some parameters provided in the checkbox i need to click. the gui is running but i need some help for the code lines for the checkboxes. what do i need to add that the code is running fone when i click the checkboxes? for example if i just click checkbox 1 i get an error the username is to long even i name the testaccount "testuser"
$PSDefaultParameterValues['*:Encoding'] = 'ascii'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#create form
$form = New-Object System.Windows.Forms.Form
$form.Width = 500
$form.Height = 400
$form.MaximizeBox = $false
$form.TopMost = $true
$objLabel = New-Object System.Windows.Forms.label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(130,15)
$objLabel.BackColor = "Transparent"
$objLabel.ForeColor = "Black"
$objLabel.Text = "name"
$Form.Controls.Add($objLabel)
#textbox with choosen user name
$txtBox = New-Object System.Windows.Forms.TextBox
$txtBox.Location = New-Object System.Drawing.Point (180, 20)
$txtBox.Size = New-Object System.Drawing.Size(280,100)
$form.Controls.Add($txtBox)
$objLabel2 = New-Object System.Windows.Forms.label
$objLabel2.Location = New-Object System.Drawing.Size(10,50)
$objLabel2.Size = New-Object System.Drawing.Size(130,15)
$objLabel2.BackColor = "Transparent"
$objLabel2.ForeColor = "Black"
$objLabel2.Text = "password"
$Form.Controls.Add($objLabel2)
#textbox with choosen password
$txtBox2 = New-Object System.Windows.Forms.TextBox
$txtBox2.Location = New-Object System.Drawing.Point (180, 50)
$txtBox2.Size = New-Object System.Drawing.Size(280,100)
$form.Controls.Add($txtBox2)
#create checkbox1
$checkBox = New-Object System.Windows.Forms.CheckBox
$checkBox.Location = New-Object System.Drawing.Point (10, 100)
$checkBox.Size = New-Object System.Drawing.Size(350,30)
$checkBox.Text = "PasswordNeverExpires"
$form.Controls.Add($checkBox)
#create checkbox2
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox2.Location = New-Object System.Drawing.Point (10, 150)
$checkBox2.Size = New-Object System.Drawing.Size(350,30)
$checkBox2.Text = "UserMayChangePassword"
$form.Controls.Add($checkBox2)
#create checkbox2
$checkBox3 = New-Object System.Windows.Forms.CheckBox
$checkBox3.Location = New-Object System.Drawing.Point (10, 200)
$checkBox3.Size = New-Object System.Drawing.Size(350,30)
$checkBox3.Text = "AccountNeverExpires"
$form.Controls.Add($checkBox3)
#create user button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(10,250)
$Button.Size = New-Object System.Drawing.Size(150,50)
$Button.Text = "create user"
$Button.Add_Click({
if(($checkBox.Checked -eq $false) -and ($checkBox2.Checked -eq $false) -and ($checkBox3.Checked -eq $false)) {
[System.Windows.Forms.Messagebox]::Show("No CheckBox checked")
}
#checkbox1 action
if ($checkBox.Checked -eq $true) {
$adminName = $txtBox
$securePassword = $txtBox2
$newUser = New-LocalUser -Name $adminName -Password $securePassword -Description $adminName -FullName $adminName #-ErrorAction Stop
$newUser | Set-LocalUser <#-PasswordNeverExpires $true#> -UserMayChangePassword $false <#-AccountNeverExpires#> #-ErrorAction Stop
Add-LocalGroupMember -Group "Administrators" -Member $adminName #-ErrorAction Stop
if(-not $?) {[System.Windows.Forms.MessageBox]::Show( "no success",'','OK',"Error")}
else {[System.Windows.Forms.MessageBox]::Show( "success",'','OK',"Information")}
}
#checkbox2 action
if ($checkBox2.Checked -eq $true) {
if(-not $?) {[System.Windows.Forms.MessageBox]::Show( "no success",'','OK',"Error")}
else {[System.Windows.Forms.MessageBox]::Show( "success",'','OK',"Information")}
}
#checkbox3 action
if ($checkBox3.Checked -eq $true) {
if(-not $?) {[System.Windows.Forms.MessageBox]::Show( "no success",'','OK',"Error")}
else {[System.Windows.Forms.MessageBox]::Show( "success",'','OK',"Information")}
}
})
$form.Controls.Add($Button2)
#end
[void]$form.ShowDialog()

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

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.

Use Powershell to simulate right-clicking an Active Directory Group's Properties

Just for clarification, I want the GUI to appear, like the actual window. This is for a side-project I've been trying to work on for a while now the goal was to make a faster way to link a group of users and folder. Since this is a process focusing on saving time, I wanted to have this method of going straight to the properties without having to actively search out the folder.
Ask if more info is needed
Code can be provided (Not sure why you'd need it Id prefer not, but I can be arranged)
I'd REALLY prefer to not use any kind of outside sources or installs. The main goal was to have this powershell script capable of just being put on any ol' computer and have it work. (Not really any old computer but you get my point)
I looked into RUNDLL32 dsquery,OpenQueryWindow as an option, but it didn't give me what I needed.
TL:DR - Pretty much what the title says. I want to be able to run this command and have a specific Security Group's Properties Window appear as if I was in Active Directory myself right clicking on properties.
#######Paths#########
param (
$MYDRIVE_PATH = "\\------\KSD\",
$LOG_FILE_PATH = "C:\Users\Documents\Test_Docs\",
$UserListFile = "C:\Users\Documents\Test_Docs\brenda.txt"
)
##########################
Add-PSSnapin Quest.ActiveRoles.ADManagement
#import-module activedirectory
$LogFile = $LOG_FILE_PATH + "\CreateMyDriveFolderAndPermissions_" + (Get-Date -Format "MM-d-y.h.m.s.ms") + ".log"
$groupRights = [System.Security.AccessControl.FileSystemRights]"ListDirectory, ReadData, WriteData, CreateFiles, CreateDirectories, AppendData, ReadExtendedAttributes, WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles, ReadAttributes, WriteAttributes, Write, ReadPermissions, Read, ReadAndExecute, Synchronize"
$InheritanceFlag = ([System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$ErrorCount = 0
$DestinationCheck = 1
$FolderNameCheck = 1
####################################### Option Box #######################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Options"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$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()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close();})
$objForm.Controls.Add($CancelButton)
$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 = "Options:"
$objForm.Controls.Add($objLabel)
$objBrenda = New-Object System.Windows.Forms.checkbox
$objBrenda.Location = New-Object System.Drawing.Size(10,50)
$objBrenda.Size = New-Object System.Drawing.Size(200,20)
$objBrenda.Checked = $false
$objBrenda.Text = "Brenda Fernandez"
$objForm.Controls.Add($objBrenda)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
##############################################################################################
####################################### Destination Box #######################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
##### Main Box Creation #####
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "New Folder Destination"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$x=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
###################
##### "Ok" Button Creation #####
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close();$DestinationCheck = 0})
$objForm.Controls.Add($OKButton)
###################
##### "Cancel" Button Creation #####
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close();[System.Environment]::Exit(0)})
$objForm.Controls.Add($CancelButton)
###################
##### Message Right Above Selection Box #####
$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 = "Select a Folder:"
$objForm.Controls.Add($objLabel)
###################
##### List Selection #####
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(10,40)
$objListBox.Size = New-Object System.Drawing.Size(260,20)
$objListBox.Height = 80
##### Options for Path #####
[void] $objListBox.Items.Add("Department")
[void] $objListBox.Items.Add("Engagement")
[void] $objListBox.Items.Add("Project")
[void] $objListBox.Items.Add("Opportunity")
###################
$objForm.Controls.Add($objListBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
###Path Creation###
$MYDRIVE_PATH = $MYDRIVE_PATH + $x
###################
$ParentFolder = $x
################################################################################################
####################################### Name Box #######################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$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()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close();$FolderNameCheck = 0})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close();[System.Environment]::Exit(0)})
$objForm.Controls.Add($CancelButton)
$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 = "Enter File 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(260,20)
$objForm.Controls.Add($objTextBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$FolderName = $x
#if([string]::IsNullOrEmpty($FolderName)){$FolderNameCheck = 1}
$SecurityName = "US-SG " + $FolderName
################################################################################################
if( $objBrenda.Checked -eq $true ) # Checks if it is a Brenda Fernandez folder and if so adds _QPC to the security group name
{
$SecurityName = $SecurityName + "_QPC"
}
if($FolderNameCheck -eq 0 -and $DestinationCheck -eq 0 ) #Failsafe to make sure all information has been filled out
{
#####Create Security Group#####
$Description = $ParentFolder + "\" + $FolderName
New-QADGroup -Name $SecurityName -samAccountName $SecurityName -Description $Description -GroupScope DomainLocal -ParentContainer "------------"
##################################
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($SecurityName,$groupRights,$InheritanceFlag, $PropagationFlag,"Allow") #Adds all the security options to the variable $Ar
$UserFolder = New-Item -Path ('{0}\{1}' -f $MYDRIVE_PATH,$FolderName) -ItemType Directory # Creates New Folder
$Acl = get-acl -Path $UserFolder.FullName #Finds location of Folder's Security group
while(1) { #Waits for Security Group to be created and appear in Active Directory
if( $Acl.SetAccessRule($Ar) -eq $NULL ){ break; } ########### Once Completed it will set the $Ar to $Acl and break out of the loop
Start-Sleep -s 1
}
$Acl | Set-Acl $UserFolder.FullName #####Set security group to user folder
##################### Notification Popup ##########################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = "C:\Users\Downloads\success.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipText = "The folder " + $FolderName + " has been successfully created."
$objNotifyIcon.BalloonTipTitle = "Proccess Complete"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
Start-Sleep -s 1
$objNotifyIcon.Dispose()
##############################################################################################
if( $objBrenda.Checked -eq $true )
{
$DPText = "US\" + $SecurityName + "_QPC;"
Add-Content $UserListFile $DPText
}
}
if ($ErrorCount -eq 0)
{
Write-Host "Done." -ForegroundColor Green
}
else{
Write-Host "Done. ($ErrorCount)" -ForegroundColor Red
}
<#
if(() -ne $Null)
{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = "C:\Users\Downloads\success.ico"
$objNotifyIcon.BalloonTipIcon = "Error"
$objNotifyIcon.BalloonTipText = "The security group " + $FolderName + " already exists."
$objNotifyIcon.BalloonTipTitle = "Something went horribly wrong!"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
Start-Sleep -s 1
$objNotifyIcon.Dispose()
exit
}
#>
#[Windows.Clipboard]::SetText("Meow")
I think you're getting WAY too complicated. I would try using the ActiveDirectory module installed with RSAT (Remote Server Administration Tools). Don't be afraid to leave the GUI, it's not that scary once you get used to it. :)
Really, I mean you could probably do this with a one-liner.