Powershell if else statement - powershell

I am having some difficulties with my Powershell script. With this script I am able to enable disabled AD accounts. It works, but I am receiving the wrong output. Accounts got enabled, but still receive the output from the else statement 'Account has not been enabled'. Anyone who can help me? Thanks!
Add-Type -AssemblyName System.Windows.Forms
$SystemInfoForm = New-Object System.Windows.Forms.Form
$SystemInfoForm.ClientSize = "300,100"
$SystemInfoForm.Text = "Enable AD Accounts"
$SystemInfoForm.BackColor = "#ffffff"
$SystemInfoForm.StartPosition = "CenterScreen"
$objIcon = New-Object system.drawing.icon ("C:\Temp\System Info.ico")
$SystemInfoForm.Icon = $objIcon
$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 = 'Please enter the disabled AD account below:'
$SystemInfoForm.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$textBox.Text = "Enter AD account..."
$SystemInfoForm.Controls.Add($textBox)
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(10,70)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click(
{
$Username = $textBox.Text
if (Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount)
{
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else
{
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
}
)
$SystemInfoForm.Controls.Add($okButton)
[void]$SystemInfoForm.ShowDialog()
Regards,
Ralph

Enable-ADAccount doesn't return any output by default, so the entire pipeline expression:
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount
... will evaluate to nothing - and all of that nothing evaluates to $false in your if condition.
Use a try/catch block to catch errors from Enable-ADAccount and then alert the based on that:
try {
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -ErrorAction Stop
# We got this far because Enable-ADAccount didn't throw any errors
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
catch {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
Alternatively use the -PassThru switch with Enable-ADAccount to have it return the account, then inspect that:
$enabledAccount = Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -PassThru
if($enabledAccount.Enabled){
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}

Related

I am wanting to return to a previous funtion in Powershell, to rectify with user error if a variable is met?

The current script is as follows;
$HN = hostname
$DN = Get-ADComputer -identity $HN -Properties DistinguishedName | select-object -ExpandProperty DistinguishedName
#*
$OU = 'OU=Workstations,DC=$domain,DC=$domain,DC=$domain'
[array]$A = Get-ADOrganizationalUnit -SearchBase $OU -SearchScope OneLevel -Filter * | Select-Object -ExpandProperty Name
[array]$DropDownArray = $A | Sort-Object
function Return-DropDown {
if ($DropDown.SelectedItem -eq $B){
$DropDown.SelectedItem = $DropDown.Items[0]
$Form.Close()
}
else{
$Form.Close()
}
}
function SelectGroup{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 600
$Form.height = 200
$Form.Text = ”DropDown”
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(140,10)
$DropDown.Size = new-object System.Drawing.Size(300,80)
ForEach ($Item in $DropDownArray) {
[void] $DropDown.Items.Add($Item)
}
$Form.Controls.Add($DropDown)
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,40)
$DropDownLabel.Text = "Select Group:"
$DropDown.Font = New-Object System.Drawing.Font("Calibri",15,[System.Drawing.FontStyle]::Bold)
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(140,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Select an Item"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
$form.ControlBox = $false
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(290,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Finish"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Move-ADObject -Identity "$DN" -TargetPath "$OU" | Return-DropDown})
$form.Controls.Add($Button)
$form.ControlBox = $false
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
$B = $dropdown.SelectedItem
return $B
}
$B = SelectGroup
I would like to develop this tool and add as an aditional option to return to the begining of the previous function;
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(290,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Back"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Return to #* })
$form.Controls.Add($Button)
$form.ControlBox = $false
Not sure how to achieve this, hoping to find help on here.
I have looked at loops and breaks but nothing seems to fit or that i can adapt to achieve this.
If you're looking for simple repetition of the form function, you could do something like this (unless your tool hides the PowerShell window).
Do {
# Move these lines from #*
$OU = 'OU=Workstations,DC=$domain,DC=$domain,DC=$domain'
[array]$A = Get-ADOrganizationalUnit -SearchBase $OU -SearchScope
OneLevel -Filter * | Select-Object -ExpandProperty Name
[array]$DropDownArray = $A | Sort-Object
$B = SelectGroup
#{... Do Work on $B, if desired ...}
$Stop = Read-Host -Prompt 'Do you want to stop?'
} Until ($Stop -match '(Y|y|Yes|YES|yes)')
Otherwise you'll need to alter your "return-dropdown" function to not close your form and implement your "back" button another way.

Get-ADUser : Cannot Validate argument 'identity'. The argument is null

I'm working on a script and part of it relies on selecting a AD user from a list box. Problem is that the selected user is coming back 'Null'. Have a look at the code below!
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Account Selection'
$form.Size = New-Object System.Drawing.Size (400,250)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point (110,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 (190,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)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point (10,0)
$label.Size = New-Object System.Drawing.Size (280,20)
$label.Text = 'Select the user account'
$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 (363,150)
$listBox.Height = 120
$form.Controls.Add($listBox)
$form.Topmost = $true
$ADUserGroup = Get-ADObject -Filter 'ObjectClass -eq "User"' -SearchBase 'OU=Users,DC=Company,DC=com' | sort name
foreach ($User in $ADUserGroup)
{
$listBox.Items.Add($User.Name) | Out-Null
}
$result = $form.ShowDialog()
#Store results
if ($result -eq 'Cancel') {exit}
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$Name = $listBox.SelectedItem
$Employee = Get-ADUser -Filter {SamAccountName -eq $Name}
}
Get-ADUser -Identity $Employee
After the user is selected we should be able to run more AD related commands using the $Employee variable. Below is the error.
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At line:69 char:22
+ Get-ADUser -Identity $Employee
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
It must be that your $Employee variable is null when it gets to the Get-ADUser -Identity $Employee call. $Employee comes from the line $Employee = Get-ADUser -Filter {SamAccountName -eq $Name}, so it must be that AD can't find a user with SamAccountName = $Name.
Write some output for the $Employee variable and see if it is indeed null. Then figure out whether the $Name variable is correct and if that person exists in AD.
I would suggest using the listboxes SelectedIndex instead of the SelectedItem property.
Also, instead of using Get-ADObject, why not use Get-ADUser in the first place.
Taken from the part where the form is built, just below $form.Topmost = $true, this should work for you:
# Get an array of all user objects in the given OU and sort by property Name
# By default, these objects will have the following properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass,
# ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# If you need more or other properties, then you need to add the -Properties
# parameter to the Get-ADUser cmdlet below.
$ADUserGroup = Get-ADUser -SearchBase 'OU=Users,DC=Company,DC=com' | Sort-Object Name
foreach ($User in $ADUserGroup) {
$listBox.Items.Add($User.Name) | Out-Null
}
$result = $form.ShowDialog()
$selectedIndex = $listBox.SelectedIndex
# close and remove the form
$form.Dispose()
# handle the results
if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $selectedIndex -ge 0) {
# store the selected AD user object in variable $Employee and do the rest of your code with it
$Employee = $ADUserGroup[$selectedIndex]
}
# $Employee now holds the ADUser object with all properties you asked for or is $null if no selection was made

Powershell select combobox and execute a mstsc.exe

I need help and i sorry because i new in IT !
I want to make a combobox who when i select a server, have a button to open a mstsc.exe
I try fill this list in the combobox with a query like this:
$1= Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=Computer, DC=example, DC=com" | select name
I try make something modificate with this example but i cant :s
[reflection.assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
function Button_OnClick() {
"`$combo.SelectedItem = $($combo.SelectedItem)" | Out-GridView
if ($combo.SelectedItem -eq 'Google') {
Start-Process -FilePath 'C:\Program Files\Internet Explorer\iexplore.exe' -ArgumentList 'http://www.google.com'
} elseif ($combo.SelectedItem -eq 'Microsoft') {
$IE = New-Object -ComObject 'InternetExplorer.Application'
$IE.Navigate2('http://www.microsoft.com')
$IE.Visible = $true
}
}
$combo = New-Object -TypeName System.Windows.Forms.ComboBox
$combo.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 5
$combo.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$combo.Items.Add('Google') | Out-Null
$combo.Items.Add('Microsoft') | Out-Null
$combo.SelectedIndex = 0
$button = New-Object -TypeName System.Windows.Forms.Button
$button.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 35
$button.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$button.Text = 'Launch in IE'
$button.Add_Click({ Button_OnClick })
$form = New-Object -TypeName System.Windows.Forms.Form
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 60, 105
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$form.Controls.Add($combo)
$form.Controls.Add($button)
$form.ShowDialog() | Out-Null
Thanks and sorry for my bad english
If I understand you correctly, you want to press a button and it will run a query and then dump the server names into the combo box. Simple.
You need to iterate through the names and add them to the combo box Item list, not the SelectedItem list.
$comboBox1.Items.Clear()
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=Computer, DC=example, DC=com" -Properties Name | select name
Foreach($name in $1) {
$comboBox1.Items.Add($Name.name)
}
Don't forget to clear the ComboBox before running it otherwise you will end up with duplicate entries.
EDIT:
To To run the mstsc.exe with the selected code, put this in your button function.
mstsc.exe /v:$($comboBox1.SelectedItem)
THanks Drew for help me!. I make the modification but now the powerbox just fill with one server.
This query its ok because i do in a powershell console and get me the full list:
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=xx, DC=xxx, DC=xxx" -Properties Name | select name
I copy the code who i try to fill de combobox1. Thanks again for the help!
[reflection.assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$comboBox1.Items.Clear()
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=xxx, DC=xxx, DC=xxx" -Properties Name | select name
Foreach($name in $1) {
$comboBox1.Items.Add($Name.name)
}
$comboBox1 = New-Object -TypeName System.Windows.Forms.ComboBox
$comboBox1.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 5
$comboBox1.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$comboBox1.Items.Add($name.name) | Out-Null
$form = New-Object -TypeName System.Windows.Forms.Form
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 60, 105
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$form.Controls.Add($combobox1)
$form.Controls.Add($button)
$form.ShowDialog() | Out-Null

Powershell: How to get powershell to give you the option to select the right user when you search with Known name

I have creates a Powershell script that takes a display name from a CSV looks up there username and then adds them to a security group in AD.
The problem is people with the same Display name. My script when it hits the same display name it will just add every user name with that display name.
I would like an option when it hits a name that returns multiple username that it displays an option that allows someone to pick the right username then add them to the security group.
I am fairly new to PowerShell and have come a bit stuck at this point so any help is greatly appreciated.
Import-Module ActiveDirectory
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Security Group Tool"
$Form.Size = New-Object System.Drawing.Size(390,150)
$Form.StartPosition = "CenterScreen"
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Icon = New-Object System.Drawing.Icon("H:\test\favicon.ico")
$Form.Icon = $Icon
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Size(10, 10)
$label.Size = New-Object System.Drawing.Size(400, 15)
$label.Text = "Please enter The name of the Security Group You want to add users too"
$Form.Controls.Add($label)
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Location = New-Object System.Drawing.Size(10,50)
$textbox.Size = New-Object System.Drawing.Size(240,40)
$Form.Controls.Add($textbox)
$test = {
$secgrp = $textbox.Text
$Sam = #()
$names = Import-Csv "H:\test\Groups2.csv"
foreach ($name in $names.DisplayName) {
$Sam += Get-ADUser -Filter { Name -like $name } -Properties SamAccountName | Select-Object SamAccountName
}
$User = $Sam
foreach ($User in $User) {
Add-ADGroupMember -Identity $secgrp -Members $User
}
}
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(260,45)
$OKButton.Size = New-Object System.Drawing.Size(75,30)
$OKButton.Text = "OK"
$OKButton.Add_Click($test)
$Form.Controls.Add($OKButton)
$Form.Add_KeyDown({
if ($_.KeyCode -eq "Enter") {
& $test
}
})
$Form.Add_KeyDown({
if ($_.KeyCode -eq "Escape") {
$Form.Close()
}
})
$Form.TopMost = $True
$Form.Add_Shown({ $Form.Activate() })
[void] $Form.ShowDialog()
You can check the number of Users returned by Get-ADUser by using the Count property. This will tell you how many objects (users) were returned.
If there is more than 1 user, you can use Out-GridView to display a popup dialogue to select the result you want from the list:
By default this allows multiple selections, but adding -OutputMode Single will then only allow a single selection to be chosen.
Your script can be updated like this:
$test = {
$secgrp = $textbox.Text
$Users = New-Object System.Collections.ArrayList
$names = Import-Csv "H:\test\Groups2.csv"
foreach ($name in $names.DisplayName) {
$ReturnedUser = Get-ADUser -Filter { Name -like $name } -Properties SamAccountName | Select-Object -ExpandProperty SamAccountName
if ($ReturnedUser.count > 1) {
$SelectedUser = $ReturnedUser | Out-GridView -Title "Multiple Users have matched, select User to process" -OutputMode Single
$null = $Users.Add($SelectedUser) #this syntax surpresses the .Add() from displaying the index of each item added
}
else {
$null = $Users.Add($ReturnedUser)
}
}
foreach ($User in $Users) {
Add-ADGroupMember -Identity $secgrp -Members $User
}
}

Powershell Codewrap for repeat option and bug with form

I got a script which is handling some things. I know a lot say I should get more short scripts which are working. But there are many people which can't handle many files or scripts and want 1 which can do all, and I can't tell 600 people which script does what. I need a kind of assembling at least of a few.
I wanted to make a workaround for the canceld options. The easiest way is to wrap all the code in a do {} while () for sure. But are there any options where I can repeat a single option? Something like when it asks do you really want to cancel.
And a real annoying bug I can't fix is that after every single action the start form blops up again. I tried out diffrent ways to debug with a counter but it didn't count up and also I tried to put the function assembling at a other place didn't fix it as well. Don't know why it happens.
Code for repro
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Set-PSDebug -Strict #Errorcall if a variable isnt declared
#Function Assembling
function Saveat()
{
#working
$Saveat = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveat.filter = "CSV (*.csv)| *.csv"
#IF selection is canceld
$result = $form.ShowDialog()
[void]$Saveat.ShowDialog()
return $Saveat.FileName
}
function Compare($location1, $location2)
{
#work in progress
$CSV1 = Import-Csv -Path $location1 -UseCulture
$CSV2 = Import-Csv -Path $location2 -UseCulture
$Compared = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 |
select -ExpandProperty inputObject |
sort
[void] $CSV1
[void] $CSV2
return $Compared
}
function whichcsv()
{
#working
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.Filter = "CSV (*.csv)| *.csv"
$result = $form.ShowDialog()
[void]$location.ShowDialog()
return $location.FileName
}
#Select which option Form
#region Initiate Form **This Form Blops up after every user action**
$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("List Filter")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("AS400 Personal Not implemented yet")
[void] $listBox.Items.Add("ADBenutzer Not implemented yet")
#endregion
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import and Filter set
$CSV = Import-Csv -Path $csvpath -UseCulture
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
$SDestination = Saveat
if ($SDestination -eq "")
{
Write-Host "Operation Canceld"
}
else
{
Write-Host "Process started"
foreach ($y1 in $y)
{
New-Object PSObject -Property #{Inventarnummer=$y1.$Filter} | Export-Csv $SDestination -NoTypeInformation -Append
}
Write-Host "Process finished"
}
}
}
#Option 2 working
"ADComputer"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import with filter
$CSV = Import-Csv -Path $csvpath -Delimiter ','
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
#Path selection
$Saveworking = Saveat
$SaveFailed = Saveat
if($Saveworking -eq "")
{
Write-Host "Operation canceld"
}
elseif ($SaveFailed -eq "")
{
Write-Host "Operation canceld"
}
else
{
#Progress
Write-Host "Process Start"
foreach($n in $y)
{
try
{
$Computer = [system.net.dns]::resolve($n.$Filter) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.$Filter $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.$Filter} | Export-Csv $Saveworking -NoTypeInformation -Append
}
catch
{
Write-Host "$($n.$Filter) is unreachable."
New-Object PSObject -Property #{Name=$n.$Filter} | Export-Csv $SaveFailed -NoTypeInformation -Append
}
}
Write-Host "Process successfull completed"
}
}
}
#Option 3 Not implemented yet
"AS400 Personal Not implemented yet"
{
Write-Host "Not implemented yet"
}
#Option 4 not implemented yet
"ADBenutzer Not implemented yet"
{
Write-Host "Not implemented yet"
}
}
}
else
{
Write-Host "Operation Canceld"
}
I guess you need to work with form events rather than .DialogResult.
For the Cancel button you would probably do something like: $CancelButton.Add_Click({[Void]$Form.Window.Close()})
For the OK button you would probably want to put the majority of your OK task in a function and invoke it from a similar event:
Function Task {
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
...
$OkButton.Add_Click({Task})
(And close the dialog ([Void]$Form.Window.Close()) when the task is completed)