How can I get rid of extra characters in TextBox? - powershell

The intent of this form is to retreive first a username then use that username to retreive an email address. it does get the address but it also retreives other characters as well. textbox3 ends up reading #{EmailAddress=first.last#domain.com}. I have tried trimming characters but that did not work.
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);'
[Console.Window]::ShowWindow([Console.Window]::GetConsoleWindow(), 0)
<#
.NAME
Template
#>
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(400,400)
$Form.text = "Form"
$Form.TopMost = $false
$TextBox1 = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline = $false
$TextBox1.width = 100
$TextBox1.height = 20
$TextBox1.location = New-Object System.Drawing.Point(61,52)
$TextBox1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TextBox2 = New-Object system.Windows.Forms.TextBox
$TextBox2.multiline = $false
$TextBox2.width = 100
$TextBox2.height = 20
$TextBox2.location = New-Object System.Drawing.Point(219,52)
$TextBox2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TextBox3 = New-Object system.Windows.Forms.TextBox
$TextBox3.multiline = $false
$TextBox3.width = 100
$TextBox3.height = 20
$TextBox3.location = New-Object System.Drawing.Point(61,130)
$TextBox3.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "button"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(228,127)
$Button1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Button1.Add_Click({getacctname})
$Form.controls.AddRange(#($TextBox1,$TextBox2,$TextBox3,$Button1))
#region Logic
function getacctname {
$fname = $TextBox1.Text
$lname = $TextBox2.Text
$User.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" |
Select-Object -ExpandProperty 'SamAccountName' |
Out-Gridview -Title 'Windows Logon' -PassThru
$TextBox3.Text = Get-ADUser -identity $User.text -Properties * | select EmailAddress
}
#endregion
[void]$Form.ShowDialog()

There are two issues with your code:
As explained in a comment, you need to get the value from the EmailAddress property of your object, otherwise, because the .Text property value can only be a string, what you will see as a result is a string representation of a PSCustomObject.
The assignment of $User.Text is invalid and will produce an error unless you're not showing us your actual code. The $User variable not defined hence cannot have a .Text property. Trying to assign anything to it will produce an error such as:
The property 'Text' cannot be found on this object. Verify that the property exists and can be set.
How should your function to solve both issues:
function getacctname {
$fname, $lname = $TextBox1.Text.Trim(), $TextBox2.Text.Trim()
$TextBox3.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" -Properties mail |
Select-Object SamAccountName, mail |
Out-Gridview -Title 'Windows Logon' -PassThru |
Select-Object -ExpandProperty mail
}
As aside, I would recommend you to make $TextBox3 a ReadOnly TextBox:
$TextBox3.ReadOnly = $true

Related

learning powershell, and having some issues with GetADUser with -Filter

So I am having some issues with the below script. The weird part is, when I run the apparently offending part separately by itself, it works fine. It's only when it tries to run in the add_Click function that it throws an error message.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$SearchTermTest=Read-Host -Prompt "Enter First or last name"
$UsersTest = Get-ADUser -Filter "GivenName -eq '$SearchTermTest' -or SurName -eq '$SearchTermTest'"
Write-Output $UsersTest
# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(500,500)
# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)
$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(150,20)
$SearchForm.Controls.Add($InputTextBox)
# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(450,400)
$SearchForm.Controls.Add($DataGridView1)
# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.Add_Click({
$SearchTerm = $InputTextBox.Text
$Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurName -eq '$SearchTerm'"
$DataGridView1.DataSource = $null
$DataGridView1.DataSource = $Users
$DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)
$SearchForm.ShowDialog()
Get-ADUser : The search filter cannot be recognized
At C:\Users\ad_forrest.vasilinda\Desktop\user password search.ps1:36 char:14
+ ... $Users = Get-ADUser -Filter "GivenName -eq '$SearchTerm' -or SurNa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Error message is above. Any ideas? I am at my wits end honestly. I have the exact same GetADUser statement running with the same filter at the beginning of the script with no errors, its only in the add_click function it throws it.
Update -- changing some of the variable names to be more descriptive and not match any of the reserved names now only causes the error to pop up when the field is left blank. However, now when there is text in the field and I push the button, nothing happens.
I was getting a blank screen as well so I changed it a bit and added some error checking. Now you can search an empty string or part of the name. I changed the filter to -Like so you get better results.
I added a variable $properties so you can add/remove the AD attributes you would like to use.
Cheers
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Properties to display
$properties = "GivenName","SurName","Mail","UserPrincipalName","Company"
# Create the form
$SearchForm = New-Object System.Windows.Forms.Form
$SearchForm.Text = "Search User"
$SearchForm.Size = New-Object System.Drawing.Size(800,500)
# Create the label and textbox for user input
$FirstLastNameLabel = New-Object System.Windows.Forms.Label
$FirstLastNameLabel.Location = New-Object System.Drawing.Size(20,20)
$FirstLastNameLabel.Text = "Enter First or Last Name"
$SearchForm.Controls.Add($FirstLastNameLabel)
$InputTextBox = New-Object System.Windows.Forms.TextBox
$InputTextBox.Location = New-Object System.Drawing.Size(160,20)
$SearchForm.Controls.Add($InputTextBox)
# Create the DataGridView
$DataGridView1 = New-Object System.Windows.Forms.DataGridView
$DataGridView1.Location = New-Object System.Drawing.Size(20,50)
$DataGridView1.Size = New-Object System.Drawing.Size(750,400)
$dataGridView1.ColumnCount = $properties.count
$dataGridView1.ColumnHeadersVisible = $true
$i=0
$properties | %{
$dataGridView1.Columns[$i++].Name = $_
}
$SearchForm.Controls.Add($DataGridView1)
# Create the search button
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(280,20)
$SearchButton.Size = New-Object System.Drawing.Size(100,20)
$SearchButton.Text = "Search"
$SearchButton.add_click({
$SearchTerm = ($InputTextBox.Text).trim()
$filter = "*"
if ($searchTerm) {
$filter = "GivenName -like '*$SearchTerm*' -or SurName -like '*$SearchTerm*'"
}
[array]$users = Get-ADUser -Filter $filter -Properties $properties | select $properties
$DataGridView1.Rows.Clear()
if ($users) {
$users | %{
$DataGridView1.Rows.Add($_.psobject.Properties.value)
}
}
$DataGridView1.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnMode]::DisplayedCells)
})
$SearchForm.Controls.Add($SearchButton)
$SearchForm.ShowDialog()

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.

Powershell Gui not releasing form Data entered into textboxes

I have a powershell form that pulls active directory information. 1 section get the account name from entering the First and Last Names into textboxes. after the results are displayed and I attempt to find another username I get the same results as the previous search or I get an error. Is there a line of code I need to clear the cache so to speak.
<#
.NAME
AD Account Tool
.SYNOPSIS
Check User by SamAccountName . Can Unlock User and lock user. Reset Password, enable nad disable user
.DESCRIPTION
Checks user by SamAccountName. Returns Name, Last LogonDate, LockedOut Status, LockedoutTime, and Enabled Status. Allows User to be unlocked and locked. Locking of user is by increasing badpasswordcount. User is able to reset password for account. Enabling and disabling of Users are allowed.
#>
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$fname= $FirstName.Text
$lname= $LastName.Text
$CheckLockTool = New-Object system.Windows.Forms.Form
$CheckLockTool.ClientSize = New-Object System.Drawing.Point(700,200)
$CheckLockTool.text = "User Account Administration Tool"
$CheckLockTool.TopMost = $false
$CheckLocked = New-Object system.Windows.Forms.Button
$CheckLocked.text = "Check Locked"
$CheckLocked.width = 100
$CheckLocked.height = 30
$CheckLocked.location = New-Object System.Drawing.Point(200,60)
$CheckLocked.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$CheckGroups = New-Object system.Windows.Forms.Button
$CheckGroups.text = "Check Groups"
$CheckGroups.width = 100
$CheckGroups.height = 30
$CheckGroups.location = New-Object System.Drawing.Point(200,89)
$CheckGroups.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$FirstName = New-Object system.Windows.Forms.TextBox
$FirstName.Text = ""
$FirstName.multiline = $false
$FirstName.width = 100
$FirstName.height = 20
$FirstName.location = New-Object System.Drawing.Point(10,30)
$FirstName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Lbl_FirstName = New-Object system.Windows.Forms.Label
$Lbl_FirstName.text = "First Name"
$Lbl_FirstName.AutoSize = $true
$Lbl_FirstName.width = 25
$Lbl_FirstName.height = 10
$Lbl_FirstName.location = New-Object System.Drawing.Point(10,10)
$Lbl_FirstName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$LastName = New-Object system.Windows.Forms.TextBox
$LastName.Text = ""
$LastName.multiline = $false
$LastName.width = 100
$LastName.height = 20
$LastName.location = New-Object System.Drawing.Point(150,30)
$LastName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Lbl_LastName = New-Object system.Windows.Forms.Label
$Lbl_LastName.text = "Last Name"
$Lbl_LastName.AutoSize = $true
$Lbl_LastName.width = 25
$Lbl_LastName.height = 10
$Lbl_LastName.location = New-Object System.Drawing.Point(150,10)
$Lbl_LastName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$User = New-Object system.Windows.Forms.TextBox
$User.Text = ""
$User.multiline = $false
$User.width = 174
$User.height = 25
$User.location = New-Object System.Drawing.Point(14,96)
$User.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Header = New-Object system.Windows.Forms.Label
$Header.text = "Enter Users 6+2"
$Header.AutoSize = $true
$Header.width = 25
$Header.height = 10
$Header.location = New-Object System.Drawing.Point(12,76)
$Header.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$UnlockAccount = New-Object system.Windows.Forms.Button
$UnlockAccount.text = "Unlock Account"
$UnlockAccount.width = 100
$UnlockAccount.height = 30
$UnlockAccount.location = New-Object System.Drawing.Point(310,60)
$UnlockAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$LockAccount = New-Object system.Windows.Forms.Button
$LockAccount.text = "Lock Account"
$LockAccount.width = 100
$LockAccount.height = 30
$LockAccount.location = New-Object System.Drawing.Point(310,89)
$LockAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$LastLogon = New-Object system.Windows.Forms.Button
$LastLogon.text = "Last Logon"
$LastLogon.width = 100
$LastLogon.height = 30
$LastLogon.location = New-Object System.Drawing.Point(425,89)
$LastLogon.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$Header2 = New-Object system.Windows.Forms.Label
$Header2.text = "Set New Password"
$Header2.AutoSize = $true
$Header2.width = 25
$Header2.height = 10
$Header2.location = New-Object System.Drawing.Point(14,137)
$Header2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Password = New-Object system.Windows.Forms.TextBox
$Password.multiline = $false
$Password.width = 174
$Password.height = 20
$Password.location = New-Object System.Drawing.Point(12,159)
$Password.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$SetPassword = New-Object system.Windows.Forms.Button
$SetPassword.text = "Set Password"
$SetPassword.width = 100
$SetPassword.height = 30
$SetPassword.location = New-Object System.Drawing.Point(200,150)
$SetPassword.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$DIsableAccount = New-Object system.Windows.Forms.Button
$DIsableAccount.text = "Disable Account"
$DIsableAccount.width = 100
$DIsableAccount.height = 30
$DIsableAccount.location = New-Object System.Drawing.Point(310,150)
$DIsableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$EnableAccount = New-Object system.Windows.Forms.Button
$EnableAccount.text = "Enable Account"
$EnableAccount.width = 100
$EnableAccount.height = 30
$EnableAccount.location = New-Object System.Drawing.Point(420,150)
$EnableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$getacctname = New-Object system.Windows.Forms.Button
$getacctname.text = "Get 6+2"
$getacctname.width = 100
$getacctname.height = 30
$getacctname.location = New-Object System.Drawing.Point(300,25)
$getacctname.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$CheckLockTool.controls.AddRange(#($Lbl_FirstName,$Lbl_LastName,$FirstName,$LastName,$getacctname,$LastLogon,$CheckGroups,$CheckLocked,$User,$Header,$UnlockAccount,$LockAccount,$Header2,$Password,$SetPassword,$DIsableAccount,$EnableAccount))
$CheckLocked.Add_Click({ CheckLocked })
$CheckGroups.Add_Click({ CheckGroups })
$UnlockAccount.Add_Click({ UnlockAccount })
$LockAccount.Add_Click({ LockAccount })
$SetPassword.Add_Click({ SetPassword })
$DIsableAccount.Add_Click({ DisableAccount })
$EnableAccount.Add_Click({ EnableAccount })
$LastLogon.Add_Click({ LastLogon })
$getacctname.Add_Click({getacctname})
#region Logic
#Write your logic code here
function SetPassword {
Set-ADAccountPassword -Identity $User.text -NewPassword (ConvertTo-SecureString -AsPlainText $Password.text -Force)
[System.Windows.MessageBox]::Show('Password Changed')
}
function CheckLocked {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Locked Accounts'
}
function CheckGroups {
$Result = Get-ADUser –Identity $User.text -Properties Name, Memberof | Select-Object -ExpandProperty MemberOf
$Result | Out-GridView -Title 'Group Memberships'
}
function LastLogon {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate| Select-Object -ExpandProperty LastLogonDate
$Result | Out-GridView -Title 'Last Logon'
}
function getacctname {
$Result = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'"| Select-Object -ExpandProperty 'SamAccountName'
$Result | Out-Gridview -Title 'Windows Logon'
}
function UnlockAccount {
Unlock-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
function LockAccount {
if ($LockoutBadCount = ((([xml](Get-GPOReport -Name "Default Domain Policy" -ReportType Xml)).GPO.Computer.ExtensionData.Extension.Account |
Where-Object name -eq LockoutBadCount).SettingNumber)) {
$Password = ConvertTo-SecureString 'NotMyPassword' -AsPlainText -Force
Get-ADUser -Identity $User.text -Properties SamAccountName, UserPrincipalName, LockedOut |
ForEach-Object {
for ($i = 1; $i -le $LockoutBadCount; $i++) {
Invoke-Command -ComputerName dc01 {Get-Process
} -Credential (New-Object System.Management.Automation.PSCredential ($($_.UserPrincipalName), $Password)) -ErrorAction SilentlyContinue
}
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
}
}
function EnableAccount {
Enable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Enabled Account'
}
function DisableAccount {
Disable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Disabled Account'
}
# Disable other types of close/exit
#$form.add_FormClosing({$_.Cancel=$true})
#Write-Output
#endregion
[void]$CheckLockTool.ShowDialog()
Solved. I had a malfunction in a function.
the correct function is below.
function getacctname {
$fname= $FirstName.Text
$lname= $LastName.Text
$Result = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'"| Select-Object -ExpandProperty 'SamAccountName'
$Result | Out-Gridview -Title 'Windows Logon'
}

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