Automatically expanded rows and columns - powershell

I am using code to open and view an XML file in datagridview, but the rows and columns are not already open like they are in excel.
I have been searching the internet for answers on how to have the data already presented like it would be in excel, but have not been able to find how to do this.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
[Void][reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[Void][System.Windows.Forms.Application]::EnableVisualStyles()
#Open File Dialog
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 = "XML (*.xml)| *.xml"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
#Save File Dialog
Function Save-FileName($initialDirectory){
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "XML (*.xml)| *.xml"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
#Create Form Functions
function Create-Form {
# Draw Form
$form1 = New-Object System.Windows.Forms.Form
$form1.ClientSize = New-Object System.Drawing.Size(725,400)
$form1.Text = "XML to DataGrid Editor"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.FormBorderStyle = 5
# Draw DataGrid
$dataGrid1 = New-Object System.Windows.Forms.DataGrid
$dataGrid1.Size = New-Object System.Drawing.Size(700,338)
$dataGrid1.Location = New-Object System.Drawing.Point (13,13)
$dataGrid1.DataBindings.DefaultDataSourceUpdateMode = 0
$dataGrid1.HeaderForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$dataGrid1.Name = "dataGrid1"
$dataGrid1.DataMember = ""
$dataGrid1.TabIndex = 0
$form1.Controls.Add($dataGrid1)
# Draw Open xml Configuration Button
$button_openxml = New-Object System.Windows.Forms.Button
$button_openxml.Size = New-Object System.Drawing.Size(150,25)
$button_openxml.Location = New-Object System.Drawing.Point(13,365)
$button_openxml.Text = "Open XML Document"
$button_openxml.Add_Click({
$xml_networkschema = Get-FileName
# Bind Data to DataGrid
$ds = New-Object System.Data.Dataset
$ds.ReadXml($xml_networkschema)
$dataGrid1.DataSource = $ds
})
$form1.Controls.Add($button_openxml)
# Save xml Configuration Button
$button_savexml = New-Object System.Windows.Forms.Button
$button_savexml.Size = New-Object System.Drawing.Size(150,25)
$button_savexml.Location = New-Object System.Drawing.Point(170,365)
$button_savexml.Text = "Save XML Document"
$button_savexml.enabled = "false"
$button_savexml.Add_Click({
$dbm_savenetworkschema = Save-FileName
$dataGrid1.DataSource.writexml($dbm_savenetworkschema)
})
$form1.Controls.Add($button_savexml)
$form1.ShowDialog()| Out-Null
}
Create-Form
what the display should like

Related

get acl from folders with file open dialog

I have built a little gui for getting the acl permissions for folders. with the path button i want to specify the folder path with a folder browser dialog and with the permissions button i want to get the acl. unfortunately the permissions button don't work because it can't get the folder path from the get-folder function. what's wrong with the function?
#################################################### Functions #######################################################
$path = Function Get-Folder ($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK")
{
$Ordner += $Ordnername.SelectedPath
}
return $Ordner
}
############################################## GetPermissions function
function GetPermissions{
#$Folder = get-folder
$Result = (Get-ACL $path).access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $Result
}
function Close{
$Form.Close()
}
###################### CREATING PS GUI TOOL #############################
#### Form settings #################################################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#### Input window with "Folder Path" label ##########################################
#$InputBox = New-Object System.Windows.Forms.TextBox
#$InputBox.Location = New-Object System.Drawing.Size(10,50)
#$InputBox.Size = New-Object System.Drawing.Size(180,20)
#$Form.Controls.Add($InputBox)
#$Label2 = New-Object System.Windows.Forms.Label
#$Label2.Text = "Folder Path:"
#$Label2.AutoSize = $True
#$Label2.Location = New-Object System.Drawing.Size(15,30)
#$Form.Controls.Add($Label2)
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path ###################################################################
$Path = New-Object System.Windows.Forms.Button
$Path.Location = New-Object System.Drawing.Size(10,10)
$Path.Size = New-Object System.Drawing.Size(150,60)
$Path.Text = "Path"
$Path.Add_Click({Get-folder})
$Path.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($Path)
#### Permissions ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Add_Click({GetPermissions})
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Add_Click({Close})
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
The reason for that mainly has to do with scoping, plus you should not write the function as $path = Function ... making it a call to the function.
Also, $Ordner += $Ordnername.SelectedPath is wrong, because you have never defined what $Ordner is in the function.
Below a rewrite of your code where I took the liberty to change some variable names to make them more self-explanatory:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
###################### CREATING PS GUI TOOL #############################
# define your selected path variable and initialize to nothing
$SelectedPath = $null
#################################################### Functions #######################################################
function Get-Folder {
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK") {
$script:SelectedPath = $Ordnername.SelectedPath # use script scoping here
$outputBox.Text = $script:SelectedPath
}
}
############################################## GetPermissions function
function Get-Permissions {
$outputBox.Text = '' # clear the textbox
if (-not [string]::IsNullOrWhiteSpace($script:SelectedPath)) {
$Result = (Get-ACL $script:SelectedPath).Access | # use script scoping here
Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $script:SelectedPath + "`r`n`r`n" + $Result
}
}
#### Form settings #################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [System.Drawing.Icon]::ExtractAssociatedIcon((Join-Path -Path $PSHOME -ChildPath 'powershell.exe'))
$Form.Icon = $Icon
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path button ###################################################################
$PathButton = New-Object System.Windows.Forms.Button
$PathButton.Location = New-Object System.Drawing.Size(10,10)
$PathButton.Size = New-Object System.Drawing.Size(150,60)
$PathButton.Text = "Path"
$PathButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$PathButton.Add_Click({Get-Folder})
$Form.Controls.Add($PathButton)
#### Permissions button ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$Permissions.Add_Click({Get-Permissions})
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$Close.Add_Click({$Form.Close()})
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
# destroy the form from memory
$Form.Dispose()

Use script variable inside textbox form

I’m trying to create a form which contains a message where I want to use some data imported from a CSV file.
The script will read the CSV rows and print a message that will contain data from it.
The issue is that the variables inside message textbox is not used instead a plain text is filled.
I think that this is related to System.Windows.Forms.TextBox but I can't figure it out
Any idea how I can resolve this?
Regards,
Adrian
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
function show_menu {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$form = New-Object System.Windows.Forms.Form
$form.Text = 'menu'
$form.Size = New-Object System.Drawing.Size(630,370)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedSingle'
#$form.Icon = [System.Drawing.Icon]::FromHandle((New-Object System.Drawing.Bitmap -Argument $stream).GetHIcon())
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(200,295)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click({
$form.Tag = $textBox_recipient.Text;
$form.Tag = $textBox_message.Text;
$form.Close()
})
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(355,295)
$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)
$textBox_recipient = New-Object System.Windows.Forms.TextBox
$textBox_recipient.Location = New-Object System.Drawing.Point(210,70)
$textBox_recipient.Size = New-Object System.Drawing.Size(245, 20)
$textBox_recipient.ReadOnly = $true
$form.Controls.Add($textBox_recipient)
##
$textBox_recipient_select = New-Object System.Windows.Forms.Button
$textBox_recipient_select.Location = New-Object System.Drawing.Point(460, 70)
$textBox_recipient_select.Size = New-Object System.Drawing.Size(100, 20)
$textBox_recipient_select.Text = "Select CSV file"
$textBox_recipient_select.add_Click({
$ofd = New-Object system.windows.forms.Openfiledialog
#$ofd.Filter = 'Supported file types (*.csv,*.xlsx)|*.csv,*.xlsx'
$ofd.Filter = 'Supported file types (*.csv, *.xlsx)|*.csv; *.xlsx| All (*.*)|*.*'
$script:recipient_filename = 'Not found'
if ($ofd.ShowDialog() -eq 'Ok') {
$script:recipient_filename = $textbox_recipient.Text = $ofd.FileName
}
})
#$textBox_recipient.Text = "C:\Users\Ady\Desktop\test.csv"
$form.Controls.Add($textBox_recipient_select)
$label_message = New-Object System.Windows.Forms.Label
$label_message.Location = New-Object System.Drawing.Point(10,150)
$label_message.Size = New-Object System.Drawing.Size(200,20)
$label_message.BackColor = [System.Drawing.Color]::FromName("Transparent")
$label_message.Font = [System.Drawing.Font]::new("Microsoft Sans Serif", 10, [System.Drawing.FontStyle]::Bold)
$label_message.Text = 'Message:'
$form.Controls.Add($label_message)
$textBox_message = New-Object System.Windows.Forms.TextBox
$textBox_message.Multiline = $True
$textBox_message.Scrollbars = "Vertical"
$textBox_message.Location = New-Object System.Drawing.Point(210,150)
$textBox_message.Size = New-Object System.Drawing.Size(350, 135)
$textBox_message.Text = "Insert your text here. HTML format supported"
$form.Controls.Add($textBox_message)
$form.Topmost = $true
$form.Add_Shown({ $textBox_recipient.Select(),$textBox_message.Select() })
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$script:filename = "$(($textBox_recipient).Text)"
$recipients = Import-csv -Path "$filename"
$total_recipient_nr = get-content "$filename" | select-string "#" | measure-object -line
$recipient_nr = 0
foreach ($recipient in $recipients) {
if (++$recipient_nr % 31 -eq 0)
{
Start-Sleep -Seconds 30
echo "waiting 1 minute"
}
$script:user_email = $recipient.email
$script:user_firstname = $recipient.firstname
$script:user_lastname = $recipient.lastname
$script:user_code = $recipient.code
$script:message = $textBox_message.Text
Write-Host $message
}
}
}
show_menu
For example, the following csv:
firstname, lastname, email, code ---- header of csv file
firstname1, lastname1, email1#domain, code1
firstname2, lastname2, email2#domain, code2
What I want to do is to use variables like $user_email, $user_code inside "$textBox_message.Text" field of the form and for each line of the CSV file, the message to use the value of those variables. (recipient is a row from the csv file that contains different values at each foreach run)
$script:user_firstname = $recipient.firstname
$script:user_code = $recipient.code
$script:message = $textBox_message.Text
I run the script, the form appears and I replace the default text "Insert your text here. HTML format supported" of $textBox_message.Text with the following:
Hi $user_firstname. This is your code: $user_code
The result (value of $message var) by executing line 96, should be:
Hi firstname1. This is your code: code1 - at first run of foreach loop
and
Hi firstname2. This is your code: code2 - at second run of foreach loop
Instead, the result is:
Hi $user_firstname. This is your code: $user_code --- plain text (the value) of $message
This is from what I have observed from Powershell when trying to writing a simple string with variables:
if you use single quotes i.e.
$firstName = "John"
write-host 'First name is $firstName'
The output is going to be:
First name is $firstName
However if you use double quotes, you should get the variable value instead of variable being displayed as plain text. i.e.
$firstName = "John"
write-host "First name is $firstName" or write-host "First name is $($firstName)"
you should get the desired output:
First name is John

Why OpenFileDialog found if execute from ISE but not from cmd?

I have an GUI, I want to open a folder and select a file. When I execute my code from ISE, it works. but when I run from another environment with cmd, it shows some error
Exception calling "ShowDialog" with "0" arguument(S): "Creating an instance of the COM component with CLSID.....
Function Sel_File
{
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = "P:\Temp\MM"
$OpenFileDialog.Title = "Please Select File"
$OpenFileDialog.filter = “All files (*.*)| *.*”
If ($OpenFileDialog.ShowDialog() -eq "Cancel")
{
[System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0,
[System.Windows.Forms.MessageBoxIcon]::Exclamation)
} $Global:SelectedFile = $OpenFileDialog.SafeFileName
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.AutoSize = $true
$Form.text = "Auto GM Creation"
$Form.TopMost = $true
#----------------------
$ChooseML_L = New-Object system.Windows.Forms.Label
$ChooseML_L.text = "MLs"
$ChooseML_L.AutoSize = $true
$ChooseML_L.width = 25
$ChooseML_L.height = 10
$ChooseML_L.location = New-Object System.Drawing.Point(28,20)
$ChooseML_L.ForeColor = "#000000"
$SelectML = New-Object system.Windows.Forms.TextBox
$SelectML.AutoSize = $true
$SelectML.width = 150
$SelectML.height = 30
$SelectML.location = New-Object System.Drawing.Point(120,40)
$SelectML.Text = "Selected ML"
$ChooseML = New-Object System.Windows.Forms.Button
$ChooseML.text = "Select File"
$ChooseML.AutoSize = $true
$ChooseML.width = 90
$ChooseML.height = 20
$ChooseML.location = New-Object System.Drawing.Point(28,38)
$ChooseML.ForeColor = "#ffffff"
$ChooseML.BackColor = "#093c76"
$ChooseML.Add_Click({Sel_File
$SelectML.Text = $Global:SelectedFile
})
#----------
$Apply = New-Object system.Windows.Forms.Button
$Apply.BackColor = "#6996c8"
$Apply.text = "Apply"
$Apply.width = 99
$Apply.height = 30
$Apply.location = New-Object System.Drawing.Point(320,190)
#----------
$Cancel = New-Object system.Windows.Forms.Button
$Cancel.BackColor = "#6996c8"
$Cancel.text = "Cancel"
$Cancel.width = 98
$Cancel.height = 30
$Cancel.location = New-Object System.Drawing.Point(450,190)
$Cancel.Add_Click({$Form.Close()})
#-----------
$Prefix = New-Object system.Windows.Forms.Label
$Prefix.text = "Prefix"
$Prefix.AutoSize = $true
$Prefix.width = 25
$Prefix.height = 10
$Prefix.location = New-Object System.Drawing.Point(28,80)
$Prefix.ForeColor = "#000000"
$NB = New-Object system.Windows.Forms.RadioButton
$NB.text = "NB"
$NB.AutoSize = $true
$NB.BackColor = "#4a90e2"
$NB.width = 104
$NB.height = 20
$NB.location = New-Object System.Drawing.Point(28,100)
$DPC = New-Object system.Windows.Forms.RadioButton
$DPC.text = "DPC"
$DPC.AutoSize = $true
$DPC.BackColor = "#4a90e2"
$DPC.width = 104
$DPC.height = 20
$DPC.location = New-Object System.Drawing.Point(100,100)
$Form.Controls.AddRange(#($ChooseML, $Prefix, $ChooseML_L, $Apply, $Cancel, $SelectML, $NB, $DPC))
[void]$Form.ShowDialog()
This is my code updated. This is working using PS ISE, but I tried execute it from WinPE environment, It shows those error above.
Could anyone help me please. Thank you
this works ... but i think the use of LoadWithPartialName has been deprecated. i can't find the "new way" at this time, tho. [blush]
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") |
Out-Null
$SelectFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$SelectFileDialog.InitialDirectory = 'c:\temp'
$SelectFileDialog.Filter = 'Extensionless files (*)|*'
$SelectFileDialog.Title = 'Please select a file and then click [OK]'
$SelectFileDialog.ShowDialog() |
Out-Null
$SelectFileDialog.FileName
I believe it'll work if you remove | Out-Null from this line
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog | Out-Null
Just need to add this, it works well.
Thank you for all the contribution
$OpenFileDialog.AutoUpgradeEnabled =$false

Update ComboBox Once item is selected

I'm lost and could really use some help. I'm trying to update a combo box with a list of column names from a csv file (selected by the open file button, and string input into textbox).
Function GetFileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
Function GetColumnsFromFile
{
Param ($fileWithPath)
[string]$csvFileColumnTitles = Get-Content $fileWithPath -totalcount 1
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace ",", "|").Trim()
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace "`"", "").Trim()
[String[]]$listOfColumnTitles = $csvFileColumnTitles.Split('|',[System.StringSplitOptions]::RemoveEmptyEntries)
return $listOfColumnTitles
}
Function GUIBox
{
# Creates GUI Box In Memory
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.drawing
$Form = New-Object system.Windows.Forms.Form
$Form.Width = '1200'
$Form.Height = '800'
# TabControl
$TabControl = New-Object System.Windows.Forms.TabControl
$TabControl.Name = "TabControl"
$TabControl.TabIndex = 4
$TabControl.SelectedIndex = 0
$TabControl.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$TabControl.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$TabControl.Size = $System_Drawing_Size
$Form.Controls.Add($TabControl)
# Test 1 Tab
$Test1_Tab = New-Object System.Windows.Forms.TabPage
$Test1_Tab.DataBindings.DefaultDataSourceUpdateMode = 0
$Test1_Tab.Name = "Test 1"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$Test1_Tab.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$Test1_Tab.Size = $System_Drawing_Size
$Test1_Tab.TabIndex = 1
$Test1_Tab.Text = "Test 1"
$Test1_Tab.UseVisualStyleBackColor = $True
$TabControl.Controls.Add($Test1_Tab)
# Open File Label
$SelectSourceFile_Label = New-Object System.Windows.Forms.Label
$SelectSourceFile_Label.Location = "10, 30"
$SelectSourceFile_Label.Name = "label"
$SelectSourceFile_Label.Size = "120, 20"
$SelectSourceFile_Label.TabIndex = 3
$SelectSourceFile_Label.Text = "Select Source File"
$Test1_Tab.Controls.Add($SelectSourceFile_Label)
# Open File Textbox
$SelectSourceFile_Textbox = New-Object System.Windows.Forms.TextBox
$SelectSourceFile_Textbox.Location = '10, 50'
$SelectSourceFile_Textbox.Size = '200, 20'
$SelectSourceFile_Textbox.TabIndex = 3
$SelectSourceFile_Textbox.Text = $Test1_FileInput_Textbox_String
$Test1_Tab.Controls.Add($SelectSourceFile_Textbox)
# Open File Button
$SelectSourceFile_Button = New-Object System.Windows.Forms.Button
$SelectSourceFile_Button.DialogResult = 'None'
$SelectSourceFile_Button.Location = '210, 50'
$SelectSourceFile_Button.Name = 'Open File Button'
$SelectSourceFile_Button.Size = '75, 25'
$SelectSourceFile_Button.TabIndex = 3
$SelectSourceFile_Button.Text = 'Open File'
$SelectSourceFile_Button.UseVisualStyleBackColor = $true
$SelectSourceFile_Button_Click = {$SelectSourceFile_Textbox.Text = GetFileName}
$SelectSourceFile_Button.add_Click($SelectSourceFile_Button_Click)
$Test1_Tab.Controls.Add($SelectSourceFile_Button)
# Select Open File Columns Label
$SelectSourceFileColumn_Label = New-Object System.Windows.Forms.Label
$SelectSourceFileColumn_Label.Location = "10, 90"
$SelectSourceFileColumn_Label.Name = "label"
$SelectSourceFileColumn_Label.Size = "150, 20"
$SelectSourceFileColumn_Label.TabIndex = 3
$SelectSourceFileColumn_Label.Text = "Select Source File Column"
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Label)
# Select Open File Columns Dropdown
[String[]]$ColumnList = GetColumnsFromFile 'C:\Scripts\Tests\1Project\Test.csv'
Write-Host '$ColumnList =' $ColumnList
$SelectSourceFileColumn_Dropdown = New-Object 'System.Windows.Forms.ComboBox'
$SelectSourceFileColumn_Dropdown.FormattingEnabled = $True
$SelectSourceFileColumn_Dropdown.Location = '10, 110'
$SelectSourceFileColumn_Dropdown.Name = 'File Column'
$SelectSourceFileColumn_Dropdown.Size = '200, 20'
$SelectSourceFileColumn_Dropdown.TabIndex = 3
$SelectSourceFileColumn_Dropdown.Height = 30
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Dropdown)
## Display GUI Box ##
$Form.ShowDialog()
}
GUIBox
The csv file...
"ColumnOne","ColumnTwo","ColumnThree"
"ColumnOneValueOne","ColumnTwoValueOne","ColumnThreeValueOne"
"ColumnOneValueTwo","ColumnTwoValueTwo","ColumnThreeValueTwo"
"ColumnOneValueThree","ColumnTwoValueThree","ColumnThreeValueThree"
So in the powershell window, we can see it is able to print the 3 column names. I know if I try this line [String[]]$ColumnList = GetColumnsFromFile $SelectSourceFile_Textbox.Text (replacing line 110), it will error out (because it will iterate through this line, before the user has a chance to input the selected file). So how would I update the combobox (with column names from the csv file) after the user has input their csv file?
One way you could do this is to use the button click to show the FolderBrowserDialog and if you get a filename from it, get the headings and add each one to the combobox.
You can use the same technique to populate the ComboBox when the user types into the textbox by creating a TextChanged event.
I got this to work using the following code:
function GUIBox {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$textbox1 = New-Object 'System.Windows.Forms.TextBox'
$combobox1 = New-Object 'System.Windows.Forms.ComboBox'
$buttonLoadCsv = New-Object 'System.Windows.Forms.Button'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
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 = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
$form1_Load={
#TODO: Initialize Form Controls here
}
$buttonLoadCsv_Click={
#TODO: Place custom script here
$file = Get-FileName -initialDirectory $env:USERPROFILE
if ($file)
{
$textbox1.Text = $file
try
{
$headers = Import-Csv -Path $file | Get-Member | Where-Object -FilterScript {$_.MemberType -eq 'NoteProperty'} | Select-Object -ExpandProperty Name -Unique
Write-Host ($headers | Out-String)
$combobox1.Items.Clear()
foreach($header in $headers)
{
$combobox1.Items.Add($header)
}
}
catch
{
Write-Warning -Message "The following error occured while trying to get the headings for csv file $file`: $($_.Exception.Message)"
}
}
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonLoadCsv.remove_Click($buttonLoadCsv_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($textbox1)
$form1.Controls.Add($combobox1)
$form1.Controls.Add($buttonLoadCsv)
$form1.ClientSize = '390, 76'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# textbox1
#
$textbox1.Location = '12, 14'
$textbox1.Name = 'textbox1'
$textbox1.Size = '284, 20'
$textbox1.TabIndex = 2
#
# combobox1
#
$combobox1.DropDownStyle = 'DropDownList'
$combobox1.FormattingEnabled = $True
$combobox1.Location = '12, 40'
$combobox1.Name = 'combobox1'
$combobox1.Size = '284, 21'
$combobox1.TabIndex = 1
#
# buttonLoadCsv
#
$buttonLoadCsv.Location = '302, 12'
$buttonLoadCsv.Name = 'buttonLoadCsv'
$buttonLoadCsv.Size = '75, 49'
$buttonLoadCsv.TabIndex = 0
$buttonLoadCsv.Text = 'Load Csv'
$buttonLoadCsv.UseVisualStyleBackColor = $True
$buttonLoadCsv.add_Click($buttonLoadCsv_Click)
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
GUIBox | Out-Null

Powershell - get ad user information based on a dropdown.text value

I folks,
I've try my best to handle a LDAP query on a button click, but I can get the dropdown2.text to search a name instead I put the complet name like "smith, peter".
What I want is, if I put any of first name or Last name in the "Manager" field, the click button will searh and return me all the corresponding value in Active Directory event if it's a name or a family name. I'm not far, but I can't find where is my mistake
function GenerateForm {
set-Location c:\
add-PSSnapin quest.activeroles.admanagement
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$searchldap = New-Object System.Windows.Forms.Button
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown2 = new-object System.Windows.Forms.ComboBox
#Handler
$handler_searchldap_click=
{
$manager = ""
$dropdown2.items.clear()
$manager = get-aduser -f {name -like $dropdown2.text}
foreach ($thing in $manager){
$useraccountname = $thing.name
$DropDown2.Items.Add($useraccountname) | Out-Null
}
}
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$form1.Text = "User Creation software"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 400
$System_Drawing_Size.Height = 200
$form1.ClientSize = $System_Drawing_Size
$DropDownArray = "Site1" , "Site2" , "Site3"
$DropDown2.Location = new-object System.Drawing.Size(125,80)
$DropDown2.Size = new-object System.Drawing.Size(150,27)
$dropdown2.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown2.TabIndex = 5
$dropdown2.Name = "dropdown2"
$DropDown2.add_TextUpdate({ Write-Host "TextUpdate. Updated text is: $($Dropdown2.Text)" })
$Form1.Controls.Add($DropDown2)
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDownLabel2.Location = new-object System.Drawing.Size(50,80)
$DropDownLabel2.size = new-object System.Drawing.Size(50,27)
$DropDownLabel2.Text = "Manager:"
$Form1.Controls.Add($DropDownLabel2)
$DropDown.Location = new-object System.Drawing.Size(125,55)
$DropDown.Size = new-object System.Drawing.Size(150,27)
$dropdown.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown.TabIndex = 4
$dropdown.Name = "dropdown1"
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(50,58)
$DropDownLabel.size = new-object System.Drawing.Size(50,27)
$DropDownLabel.Text = "Location:"
$Form1.Controls.Add($DropDown)
$Form1.Controls.Add($DropDownLabel)
ForEach ($Item in $DropDownArray) {
$DropDown.Items.Add($Item) | Out-Null
}
###Button section
$searchldap.Location = New-Object System.Drawing.Size(275,80)
$searchldap.Size = New-Object System.Drawing.Size(100,20)
$searchldap.Text = "Search"
$searchldap.Add_Click($handler_searchldap_click)
$Form1.Controls.Add($searchldap)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #end of function
GenerateForm
Try this:
$filter = [scriptblock]::Create("Name -like '*$($dropdown2.text)*'")
$manager = get-aduser -f $filter
Powershell does not expand local variables used in filter script blocks before it passes them to the DC (via the AD Gateway Service). To get around that, create the filter script block from an expandable string