My line break is not working in my text box - powershell

Spent a few hours now and google and unable to find out why this is not working
When i put a `n or `r it breaks the line but you cannot see the line its blank
I am new to PowerShell I got this script from the net and I am trying to modify it a bit
#==< StatusGroupBox >============================================================
$StatusGroupBox = New-Object System.Windows.Forms.GroupBox
$StatusGroupBox.Location = New-Object System.Drawing.Point(3, 220)
$StatusGroupBox.Size = New-Object System.Drawing.Size(272, 50)
$StatusGroupBox.TabStop = $True
$StatusGroupBox.Text = "Status"
#==< StatusBoxOutput >===========================================================
$StatusBoxOutput = New-Object System.Windows.Forms.Label
$StatusBoxOutput.BorderStyle = [System.Windows.Forms.BorderStyle]::None
$StatusBoxOutput.Font = New-Object System.Drawing.Font("Tahoma", 8.25, [System.Drawing.FontStyle]::Regular, `
[System.Drawing.GraphicsUnit]::Point, ([System.Byte](0)))
$StatusBoxOutput.Location = New-Object System.Drawing.Point(6, 235)
$StatusBoxOutput.Size = New-Object System.Drawing.Size(266, 14)
$StatusBoxOutput.Text = ""
$StatusBoxOutput.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
$StatusBoxOutput.BackColor = [System.Drawing.SystemColors]::Menu
$StatusBoxOutput.ForeColor = "Black"
# Check if Computer Name is in FQDN format. (We want the FQDN so we can get the Domain Name.)
if ($ComputerName -notlike "*.*") {
# Change Status Message.
$AdmPasswordOutput.Text = "error"
$PasswordExpiresOutput.Text = "n/a"
$StatusBoxOutput.ForeColor = "Red"
$StatusBoxOutput.Text = "Name must be a FQDN `ne.g. pc1$DefaultComputerFQDN'"
$SearchButton.Enabled = $true # Enable Search button
return
}

You have to set the Multiline property to true on the textbox. They are single line by default.

Related

Issue to create a dynamic Powershell Form, showing output data from the running the script

I have a question about a Powershell Form script that I can't quite get to work yet.
The code below does give the output I expect, but I can't manage to display the Form as it was during the initialization of 'establishing the connection'. The point is that we only want to start a program when there is connectivity with the router and the end user should also be able to see it that way, not just the end result.
Can anyone point me in the right direction to make the form dynamically show what's happening at the time when the script is running?
Ow, and also the 'Retry' ([System.Windows.Forms.DialogResult]::Retry)function does not do anything as expected... :(
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
# Init PowerShell Gui
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#---------------------------------------------------------[Form]--------------------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$LocalRCForm = New-Object system.Windows.Forms.Form
$LocalRCForm.ClientSize = '480,300'
$LocalRCForm.text = "Status router connection"
$LocalRCForm.BackColor = "#F9F9F9"
$LocalRCForm.StartPosition = "CenterScreen"
$LocalRCForm.TopMost = $true
$LocalRCForm.SuspendLayout()
$Titel = New-Object system.Windows.Forms.Label
$Titel.text = "Status router connection"
$Titel.AutoSize = $true
$Titel.width = 25
$Titel.height = 10
$Titel.location = New-Object System.Drawing.Point(20,20)
$Titel.Font = 'Microsoft Sans Serif,14,style=Bold'
$Description = New-Object system.Windows.Forms.Label
$Description.text = "To start Security Desk, wait for an established connection"
$Description.AutoSize = $false
$Description.width = 450
$Description.height = 50
$Description.location = New-Object System.Drawing.Point(20,60)
$Description.Font = 'Microsoft Sans Serif,10'
$RCStatus = New-Object system.Windows.Forms.Label
$RCStatus.text = "Status:"
$RCStatus.AutoSize = $true
$RCStatus.width = 25
$RCStatus.height = 10
$RCStatus.location = New-Object System.Drawing.Point(20,115)
$RCStatus.Font = 'Microsoft Sans Serif,10,style=Bold'
$RCFound = New-Object system.Windows.Forms.Label
$RCFound.text = "Connecting to router..."
$RCFound.AutoSize = $true
$RCFound.width = 25
$RCFound.height = 10
$RCFound.location = New-Object System.Drawing.Point(100,115)
$RCFound.Font = 'Microsoft Sans Serif,10'
$RCDetails = New-Object system.Windows.Forms.Label
$RCDetails.text = "Router succesfully connected"
$RCDetails.AutoSize = $true
$RCDetails.width = 25
$RCDetails.height = 10
$RCDetails.location = New-Object System.Drawing.Point(20,150)
$RCDetails.Font = 'Microsoft Sans Serif,10,style=Bold'
$RCTestConnection = New-Object system.Windows.Forms.Label
$RCTestConnection.text = "Checking connection"
$RCTestConnection.AutoSize =
$RCTestConnection.width = 25
$RCTestConnection.height = 10
$RCTestConnection.location = New-Object System.Drawing.Point(100,115)
$RCTestConnection.Font = 'Microsoft Sans Serif,10'
$AddRCBtn = New-Object system.Windows.Forms.Button
$AddRCBtn.BackColor = "#ff7b00"
$AddRCBtn.text = "Ok"
$AddRCBtn.width = 150
$AddRCBtn.height = 30
$AddRCBtn.location = New-Object System.Drawing.Point(300,250)
$AddRCBtn.Font = 'Microsoft Sans Serif,10'
$AddRCBtn.ForeColor = "#000"
$AddRCBtn.DialogResult = [System.Windows.Forms.DialogResult]::Yes
$CloseBtn = New-Object system.Windows.Forms.Button
$CloseBtn.BackColor = "#ffffff"
$CloseBtn.text = "Close"
$CloseBtn.width = 90
$CloseBtn.height = 30
$CloseBtn.location = New-Object System.Drawing.Point(300,250)
$CloseBtn.Font = 'Microsoft Sans Serif,10'
$CloseBtn.ForeColor = "#000"
$CloseBtn.DialogResult = [System.Windows.Forms.DialogResult]::Retry
$LocalRCForm.controls.AddRange(#($Titel,$Description,$RCStatus,$RCFound,$RCType,$AddRCBtn,$CloseBtn,$RCDetails,$routerIp,$testConnection))
#-----------------------------------------------------------[Functions]------------------------------------------------------------
function AddRC {
$RCFound.ForeColor = "#000000"
$RCFound.Text = 'Connected to Router'
}
#---------------------------------------------------------[Script]--------------------------------------------------------
# Check if router is online
$routerIp = '1.1.1.1'
$testConnection = Test-Connection $routerIp
If ($testConnection) {
$RCFound.text = "Router Ready"
$RCFound.ForeColor = "#7ed321"
$AddRCBtn.text = "Run the program"
$CloseBtn.Visible = $false
$RCDetails.Visible = $true
}else{
$RCFound.text = "Router not found"
$RCFound.ForeColor = "#D0021B"
$CloseBtn.text = "Close"
$AddRCBtn.Visible = $false
$RCDetails.Visible = $false
}
$AddRCBtn.Add_Click({ AddRC })
$LocalRCForm.Add_Shown({$testConnection.Enabled = $true; $testConnection.Start()})
return $LocalRCForm.ShowDialog()
There is too much to say about your script so let's focus on your main issue:
Your script will only show the form once the connection is tested, so the form will never display the various steps.
To achieve your goal, you should put your main code in a function and run it once the form is displayed.
function funTestConnection {
$testConnection = Test-Connection $routerIp
If($testConnection) {
$RCFound.text = "Router Ready"
$RCFound.ForeColor = "#7ed321"
$AddRCBtn.text = "Run the program"
$CloseBtn.Visible = $false
$RCDetails.Visible = $true
} else {
$RCFound.text = "Router not found"
$RCFound.ForeColor = "#D0021B"
$CloseBtn.text = "Close"
$AddRCBtn.Visible = $false
$RCDetails.Visible = $false
}
}
Also, you are trying to add a control in your form that is not a control ($testConnection). I suppose you wanted to add $RCTestConnection instead (and don't forget to take care of it's position).
# Change this line:
$LocalRCForm.controls.AddRange(#($Titel,$Description,$RCStatus,$RCFound,$RCType,$AddRCBtn,$CloseBtn,$RCDetails,$routerIp,$testConnection))
# To this line:
$LocalRCForm.controls.AddRange(#($Titel,$Description,$RCStatus,$RCFound,$RCType,$AddRCBtn,$CloseBtn,$RCDetails,$routerIp,$RCTestConnection))
Again, you use the variable $testConnection but it neither have a property enabled or a method Start(). So this line makes no sense and after having put your main code in a function, it should be replaced as follow:
# Replace this line that has no meaning
$LocalRCForm.Add_Shown({$testConnection.Enabled = $true; $testConnection.Start()})
# By this line
$LocalRCForm.Add_Shown({funTestConnection})
About retrying if not connected, [System.Windows.Forms.DialogResult]::Retry is not a function, it's a constant value so you can't expect it to do anything.
For it to be taken into account, you should use it in a way or the other.
One example would be like this:
# This code
do { $returnDialog = $LocalRCForm.ShowDialog() }
while($returnDialog -eq [System.Windows.Forms.DialogResult]::Retry)
# instead of this line
return $LocalRCForm.ShowDialog()
Finally, your function AddRC has no real impact as the form is closed when it's called (just a remark).
With all that said, you will have a functional script but it needs quite some adjustments related to what messages and information are displayed during the process (button names, labels, etc.) but at least it should do what you're expecting.

How do I indicate that a combo box has been populated with a selection?

I am attempting to create a form in Powershell. It contains a ComboBox dropdown option that I am using as a required field. Until an option is selected, the continue button will be disabled. This is the code for the ComboBox and the button enabling:
$TSTypeBox.Name = "TSType"
$TSTypeBox.Location = New-Object System.Drawing.Point(116,100)
$TSTypeBox.Size = New-Object System.Drawing.Size(145,20)
$TSTypeBox.add_MouseHover($ShowHelp)
$TSTypeBox.DropDownStyle = "DropDownList"
Foreach ($item in ("1","2","3","4","5")) {
$TSTypeBox.Items.Add($item) | Out-Null
}
$TSTypeBox.SelectedItem = $TSLocation
$handler_TSTypeBox_SelectedIndexChanged= {
If (($TSTypeBox.Text) -and ($ComputerNameBox.Text))
{
$OKButton.Enabled = 1
}
Else
{
$OKButton.Enabled = 0
}
}
$TSTypeBox.add_SelectedIndexChanged($handler_TSTypeBox_SelectedIndexChanged)
This code in particular works as intended so I'm not worried about that. I am here about the $TSTypeBox.SelectedItem = $TSLocation line that I included. I have code elsewhere that pulls the IP address of the computer the program is being run on, which is then matched against an if/elseif/else statement to determine if the computer belongs to 1 or to 2, which are options that you can see were added to the ComboBox in the code above.
That if/else statement updated the $TSLocation variable which I then use to force the selection of one of the dropdown options in the ComboBox. This works as well, but unfortunately it does not enable the continue button as I would like. I had a hard time looking up issues about this because its super particular and I am probably doing this incorrectly (I have very little experience with Powershell scripting). If you have any additional questions about this please let me know. Thanks!
Ok, this might illustrate your problem.
Just because you set the SelectedItem value to something, doesn't mean the SelectedIndex changes
#
Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
#
$TSLocation = '2'
#
$form = New-Object System.Windows.Forms.Form
$form.Text = "Test"
$form.MinimumSize = '430,495'
$form.MaximumSize = '430,545'
$form.StartPosition = 'CenterScreen'
#
# Add form objects
#
$TSTypeBox = New-Object System.Windows.Forms.ComboBox
$TSTypeBox.Name = "TSType"
$TSTypeBox.Location = '116,100'
$TSTypeBox.Size = '145,20'
$TSTypeBox.add_MouseHover($ShowHelp)
$TSTypeBox.DropDownStyle = "DropDownList"
Foreach ($item in ("1","2","3","4","5")) {
$TSTypeBox.Items.Add($item) | Out-Null
}
$ComputerNameBox = New-Object System.Windows.Forms.TextBox
$ComputerNameBox.Location = '120,20'
$ComputerNameBox.Size = '120,17'
$ComputerNameBox.Text = 'test'
$OutputBox = New-Object System.Windows.Forms.TextBox
$OutputBox.Location = '120,240'
$OutputBox.Size = '120,17'
$OkButton = New-Object System.Windows.Forms.Button
$OkButton.Location = '120,200'
$OkButton.Size = '54,24'
$OkButton.Text = 'OK'
$form.controls.AddRange(#($TSTypeBox,$OkButton,$ComputerNameBox,$OutputBox))
#
# Main Script goes here
#
$handler_TSTypeBox_SelectedIndexChanged= {
$OutputBox.Text = "SelectedIndex is " + $TSTypeBox.SelectedIndex
If (($TSTypeBox.Text) -and ($ComputerNameBox.Text))
{
$OKButton.Enabled = 1
}
Else
{
$OKButton.Enabled = 0
}
}
$TSTypeBox.add_SelectedIndexChanged($handler_TSTypeBox_SelectedIndexChanged)
#
$TSTypeBox.SelectedIndex = $TSTypeBox.FindStringExact($TSLocation)
#
# Show form
$form.ShowDialog() | Out-Null
$form.Dispose()
# End
If in doubt, always best to simplify your script and add debug ,logging or output that shows what values are changing
Now that the problem is clear - this article points you in the right direction:
How do I set the selected item in a comboBox to match my string using C#?

Powershell GUI. Selecting an item from a dynamic ListBox with subsequent unloading of user information from Active Directory Ask a question

Good afternoon, dear forum users. Please help me with the next question. I am trying to create a GUI application in Powershell GUI. Since I am a beginner in programming and knowledge, I have not decided to contact the forum for help. The essence of the application is to search by full name in the Active Directory accounts of the required employee account and view the date the password was changed for this account.
I have a ready-made code that works when entering an account login in English. At the same time, I want to implement a search in Russian. The code that I give below searches in Russian, but only in text form displays a list of accounts by name, this text can only be copied. I ask you to tell me how you can program the program so that it searches not in the form of text, full name, but in the form of elements on whose name you can click with the mouse cursor and get the result. I attach a screenshot of the program https://i.stack.imgur.com/GJ5qP.png. Thank you in advance for your help.
$Form.Size = New-Object System.Drawing.Size(460,350) # Mold size
$Form.Text ="Pass info"
$Form.AutoSize = $false
$Form.MaximizeBox = $false # button expand program
$Form.MinimizeBox = $true # minimize program button
$Form.BackColor = "#c08888" # Form color
$Form.ShowIcon = $true # Enable icon (upper left corner) $ true, disable icon
$Form.SizeGripStyle = [System.Windows.Forms.SizeGripStyle]::Hide # Prevent form stretching
#$Form.SizeGripStyle = "Hide"
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Fixed3D # Prevent form stretching _2
$Form.WindowState = "Normal"
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.Opacity = 1.0 # Form transparency
$Form.TopMost = $false #
Over other windows
########### Function start:
function Info {
$wks=$InputBox.text;
Write-Host $wks
$regex1 = "[^-a-zA-Z0-9_#.!#]+"
$regex2 = "[^-а-яА-Я0-9_#.!#]+"
If($wks -match $regex2) {
$Result1=Get-ADUser -identity $wks -Properties * | select CN -ExpandProperty CN
$outputBox.text=$Result1
$Result2=Get-ADUser -identity $wks -Properties * | select PasswordLastset -ExpandProperty PasswordLastset
$outputBox2.text=$Result2
}
If($wks -match $regex1) {
$wks2 = "$wks*"
Write-Host $wks2
$Result3=Get-AdUser -Filter 'name -Like $wks2' | Select Name -expandproperty Name| Sort Name | fl | out-string
Write-Host $Result3
#$Result3 = ($Result3 -replace ' ','_')
#$Result3 = $Result3 -split '_',2 -join ' '
$ListBox.text = $Result3
}
}
########### End Function.
############################################## Start text fields
#### Group selection of labels 2 and 3$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,230)
$groupBox.size = New-Object System.Drawing.Size(280,80)
$groupBox.text = "Info:"
$Form.Controls.Add($groupBox)
$FormLabel1 = New-Object System.Windows.Forms.Label
$FormLabel1.Text = "User AD:"
$FormLabel1.ForeColor = "#3009f1"
$FormLabel1.Font = "Microsoft Sans Serif,8"
$FormLabel1.Location = New-Object System.Drawing.Point(10,10)
$FormLabel1.AutoSize = $true
$Form.Controls.Add($FormLabel1)
$FormLabel2 = New-Object System.Windows.Forms.Label
$FormLabel2.Text = "ФИО:"
$FormLabel2.Location = New-Object System.Drawing.Point(10,25)
$FormLabel2.ForeColor = "#3009f1"
$FormLabel2.Font = "Microsoft Sans Serif,8"
$FormLabel2.AutoSize = $true
#$Form.Controls.Add($FormLabel2) # Метка явл. частью общ. Form
$groupBox.Controls.Add($FormLabel2) # Метка явл. частью groupBox
$FormLabel3 = New-Object System.Windows.Forms.Label
$FormLabel3.Text = "Дата:"
$FormLabel3.Location = New-Object System.Drawing.Point(10,47)
$FormLabel3.ForeColor = "#3009f1"
$FormLabel3.Font = "Microsoft Sans Serif,8"
$FormLabel3.AutoSize = $true
#$Form.Controls.Add($FormLabel3) # Метка явл. частью общ. Form
$groupBox.Controls.Add($FormLabel3) # Метка явл. частью groupBox
############################################ InputBox #########################################
$InputBox = New-Object System.Windows.Forms.TextBox
$InputBox.Location = New-Object System.Drawing.Size(65,5)
$InputBox.Size = New-Object System.Drawing.Size(150,20)
$Form.Controls.Add($InputBox)
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(80,20)
$outputBox.Size = New-Object System.Drawing.Size(180,20)
$outputBox.ReadOnly = $True
$groupBox.Controls.Add($outputBox)
$outputBox2 = New-Object System.Windows.Forms.TextBox
$outputBox2.Location = New-Object System.Drawing.Size(80,42)
$outputBox2.Size = New-Object System.Drawing.Size(180,42)
$outputBox2.ReadOnly = $True
$groupBox.Controls.Add($outputBox2)
############################################## ListBox
$ListBox = New-Object System.Windows.Forms.TextBox
$ListBox.Location = New-Object System.Drawing.Size(65,30)
$ListBox.Size = New-Object System.Drawing.Size(220,200)
$ListBox.MultiLine = $True #declaring the text box as multi-line
$ListBox.AcceptsReturn = $true
$ListBox.ScrollBars = "Vertical"
$ListBox.AcceptsTab = $true
$ListBox.WordWrap = $True
$ListBox.ReadOnly = $True
$Form.Controls.Add($ListBox)
############################################## End ListBox
############################################## search in Russian and in English
$regex1 = "[^-a-zA-Z0-9_#.!#]+"
$regex2 = "[^-а-яА-Я0-9_#.!#]+"
$TestName = "Mouse" # Mouse или мышь
If($TestName -match $regex1){echo "English '$TestName'"}
If($TestName -match $regex2){echo "Русский '$TestName'"}
get-aduser -filter 'name -like "*" ' | select name -expandproperty name
############################################## End search in Russian and in English
################ Button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(310,20)
$Button.Size = New-Object System.Drawing.Size(110,80)
$Button.Text = "Загрузить данные"
$Button.BackColor = "#d7f705"
$Button.Add_Click({Info})
$Form.Controls.Add($Button)
################ End Button
################ Binding a button in the program to the Enter key on the keyboard ...
$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{
# if enter, perform click
$Button.PerformClick()
}
})
################ End Binding a button
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
This is some example how is works:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$MyForm = New-Object System.Windows.Forms.Form
$MyForm.Text = "USER info Lastlogondate"
$MyForm.Size = New-Object System.Drawing.Size(500, 500)
#user info
$allinfo=$null
#change your domin info
$allinfo=Get-ADUser -filter * -SearchBase "OU=users,DC=domain,DC=local" -properties Name, SamAccountName,Lastlogondate
#select in the column user name to fill $mTextBox1.Text
$Selectuser =
{
$c = $mDataGrid1.CurrentCell.columnindex
$colHeader = $mDataGrid1.columns[$c].name
if ($colHeader -eq "SamAccountName") {
$username = $mDataGrid1.CurrentCell.Value
$mTextBox1.Text = $username
Write-Host $username
}
} #
#usernema textbox--------------------------------------------
$mTextBox1 = New-Object System.Windows.Forms.TextBox
$mTextBox1.Text = ""
$mTextBox1.Top = "20"
$mTextBox1.Left = "26"
$mTextBox1.Anchor = "Left,Top"
$mTextBox1.Size = New-Object System.Drawing.Size(170, 23)
$MyForm.Controls.Add($mTextBox1)
#gridview
$mDataGrid1 = New-Object System.Windows.Forms.DataGridView
$mDataGrid1.Text = "DataGrid1"
$mDataGrid1.Top = "60"
$mDataGrid1.Left = "27"
$mDataGrid1.Anchor = "Left,Top"
$mDataGrid1.AutoSizeColumnsMode = 16
$mDataGrid1.add_CellContentDoubleClick($Selectuser)
$mDataGrid1.Size = New-Object System.Drawing.Size(400, 330)
$MyForm.Controls.Add($mDataGrid1)
#GetAllUsers button------------------------------------------
$mButton1 = New-Object System.Windows.Forms.Button
$mButton1.Text = "Get All Users"
$mButton1.Top = "20"
$mButton1.Left = "200"
$mButton1.Anchor = "Left,Top"
$mButton1.Size = New-Object System.Drawing.Size(100, 23)
$MyForm.Controls.Add($mButton1)
$mButton1.Add_Click( { GetAllusers})
Function GetAllusers {
$mDataGrid1.DataSource = $null
$array = New-Object System.Collections.ArrayList
$result=$allinfo |Select-Object Name, SamAccountName,Lastlogondate|sort -Property Name
$array.Addrange($result)
$mDataGrid1.Datasource = ($array)
$MyForm.Refresh()
}
#exit---------------------------------------------------------
$mButton4 = New-Object System.Windows.Forms.Button
$mButton4.Text = "Exit"
$mButton4.Top = "20"
$mButton4.Left = "320"
$mButton4.Anchor = "Left,Top"
$mButton4.Size = New-Object System.Drawing.Size(120, 23)
$mButton4.Add_Click( {$MyForm.Close()})
$MyForm.Controls.Add($mButton4)
$MyForm.ShowDialog()

Variable is an empty string even after writing the string to host

I'm trying to build a little app to help admins swap powerapps ownership around in PowerShell. I'm sure this is me misunderstanding how scopes work in PowerShell but I'm stumped and need a little help.
The app is pretty simple, it queries the PowerApp environment for a list of apps, their owners, and their GUIDs and presents them in a datagridview. Users select the app they're going to change, click a button, put an email address in, and then click another button. On that click, the app grabs the user's GUID from AAD and then runs a command to flip ownership of the app to that user's GUID.
But for some reason, the second function keeps reporting that the GUID and App Name I collected in the first screen are empty strings.
Here's the whole thing (minus credential info, natch):
#Get Apps on environment
$apps = Get-AdminPowerApp -EnvironmentName $powerAppEnv
#Form Details
$ChangePowerAppOwnership = New-Object system.Windows.Forms.Form
$ChangePowerAppOwnership.ClientSize = New-Object System.Drawing.Point(500,300)
$ChangePowerAppOwnership.text = "Change PowerApp Ownership"
$ChangePowerAppOwnership.TopMost = $false
$appsLabel = New-Object system.Windows.Forms.Label
$appsLabel.text = "Available Apps"
$appsLabel.AutoSize = $true
$appsLabel.width = 25
$appsLabel.height = 10
$appsLabel.location = New-Object System.Drawing.Point(15,20)
$appsLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$availableApps = New-Object system.Windows.Forms.DataGridView
$availableApps.width = 470
$availableApps.height = 200
$availableApps.location = New-Object System.Drawing.Point(15,40)
$availableApps.MultiSelect = $false
$availableApps.SelectionMode = "FullRowSelect"
$availableApps.ColumnCount = 3
$availableApps.ColumnHeadersVisible = $true
$availableApps.Columns[0].Name = "App Name"
$availableApps.Columns[1].Name = "Current Owner"
$availableApps.Columns[2].Name = "GUID"
foreach($app in $apps){
$availableApps.Rows.Add(#($app.DisplayName,($app.Owner | Select-Object -Expand displayName),$app.AppName))
}
$promptForAdmin = New-Object system.Windows.Forms.Button
$promptForAdmin.text = "Next"
$promptForAdmin.width = 60
$promptForAdmin.height = 30
$promptForAdmin.location = New-Object System.Drawing.Point(424,260)
$promptForAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$promptForAdmin.Add_Click({ GetNewAdmin $availableApps.SelectedRows})
$adminLabel = New-Object system.Windows.Forms.Label
$adminLabel.text = "New Administrator"
$adminLabel.AutoSize = $true
$adminLabel.width = 25
$adminLabel.height = 10
$adminLabel.location = New-Object System.Drawing.Point(14,13)
$adminLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$adminEmailField = New-Object system.Windows.Forms.TextBox
$adminEmailField.multiline = $false
$adminEmailField.width = 200
$adminEmailField.height = 20
$adminEmailField.location = New-Object System.Drawing.Point(135,12)
$adminEmailField.Font = New-Object System.Drawing.Font('Segoe UI',10)
$changeAppAdmin = New-Object system.Windows.Forms.Button
$changeAppAdmin.text = "Go"
$changeAppAdmin.width = 60
$changeAppAdmin.height = 30
$changeAppAdmin.location = New-Object System.Drawing.Point(424,260)
$changeAppAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$ChangePowerAppOwnership.controls.AddRange(#($appsLabel,$availableApps,$promptForAdmin))
$ChangePowerAppOwnership.ShowDialog()
function GetNewAdmin {
param($selectedRows)
$selectedAppGuid = $selectedRows | ForEach-Object{ $_.Cells[2].Value }
$selectedAppName = $selectedRows | ForEach-Object{ $_.Cells[0].Value }
Write-Host "Selected App GUID: $selectedAppGuid" #this and the following command show values
Write-Host "Selected App Name: $selectedAppName"
$appsLabel.Visible = $false
$availableApps.Visible = $false
$promptForAdmin.Visible = $false
$changeAppAdmin.Add_Click( { AssignNewAdmin $selectedAppGuid $selectedAppName $adminEmailField.Text} )
$ChangePowerAppOwnership.controls.AddRange(#($adminLabel,$adminEmailField,$changeAppAdmin))
}
function AssignNewAdmin {
param(
$selectedAppGuid,
$selectedAppName,
$newAdminEmail
)
Write-Host "AppID: $selectedAppGuid" #this is always empty
Connect-AzureAD -Credential $credentials
$user = Get-AzureADUser -ObjectId $newAdminEmail
$newAppOwnerGuid = $user | select ObjectId
$newAppOwnerName = $user | select DisplayName
$msgBoxMessage = "Are you sure you want to grant ownership of $selectedAppName to $newAppOwnerName`?"
$msgBoxInput = [System.Windows.Forms.MessageBox]::Show($msgBoxMessage,"Confirm","YesNo","Error")
switch ($msgBoxInput){
'Yes'{
Set-AdminPowerAppOwner -AppName $selectedAppGuid -EnvironmentName $powerAppEnv -AppOwner $newAppOwnerGuid
# try{
# $ChangePowerAppOwnership.Close()
# }
# catch{
# Write-Host "Could not update this app's administrator role."
# }
}
'No' {
$ChangePowerAppOwnership.Close()
}
}
}
Move the functions to the top or at least higher than $ChangePowerAppOwnership.ShowDialog() or the script wont find them(the execution stops till you close the Form...).
The same goes for the function AssignNewAdmin as it is used in GetNewAdmin but defined later.
Courtesy of Jeroen Mostert's comment, adding GetNewClosure to my second Add_Click function did the trick.

Create AD user in a different domain

I created a series of scripts for creating domain users. Since every domain where we create users requires different parameters and conditions, I have one script for each domain. But in case of one domain I have a problem. For this domain the manual procedure is like this:
1) open dsa.msc
2) connect to the "xyz" domain (the user is being created from a server in "abc" domain)
3) Create the user (operation for 10 to 15 minutes, that's why I created the scripts)
Unfortunately, when I run my script, I get the error message, that "The server is unwilling to process the request" (That's the precise complete error message) during execution of New-ADUser cmdlet. I suppose the reason is the need to perform the step 2 in the procedure I described above. So I somehow need to simulate it in the script, but I have no idea how to do that.
This is how the command is defined:
$params = #{
'GivenName' = $First_name_val.Text
'Surname' = $Second_name_val.Text
'DisplayName' = $Display_name
'AccountPassword' = $password
'Path' = $Location_val.Text
'Name' = $User_name_val.Text
'CannotChangePassword' = $Cannot_chg_pass.Checked
'PasswordNeverExpires' = $Pass_not_expires.Checked
'ChangePasswordAtLogon' = $Must_chg_pass.Checked
'Enabled' = !($Account_disabled_val.Checked)
'Description' = $GECOS_val.Text
'Office' = "NA"
'OfficePhone' = "NA"
'Title' = $Job_Title_val.Text
'Department' = $Department_val.Text
'Company' = $Company_val.Text
'SamAccountName' = $User_name_val.Text
'UserPrincipalName' = $User_name_val.Text + "#woodplc.com"
'EmailAddress' = $Email_Address_val.Text
'PassThru' = $true
}
$New_user = New-ADUser #params
Definition of $User_name_val.Text is here:
#region Real name of the user
[void]$AD_user_creation.SuspendLayout()
$Display_name_lbl = New-Object system.Windows.Forms.Label
$Display_name_lbl.text = "User`'s real name"
$Display_name_lbl.AutoSize = $true
$Display_name_lbl.width = 25
$Display_name_lbl.height = 10
$Display_name_lbl.location = New-Object System.Drawing.Point(10,10)
$First_name_val = New-Object system.Windows.Forms.TextBox
$First_name_val.Text = "a."
$First_name_val.multiline = $false
$First_name_val.width = 120
$First_name_val.height = 20
$First_name_val.location = New-Object System.Drawing.Point(200,10)
$Second_name_val = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline = $false
$Second_name_val.width = 120
$Second_name_val.height = 20
$Second_name_val.location = New-Object System.Drawing.Point(330,10)
$Display_name_val = New-Object system.Windows.Forms.Label
$Display_name_val.Text = ""
$Display_name_val.width = 250
$Display_name_val.height = 20
$Display_name_val.location = New-Object System.Drawing.Point(200,40)
$showFullName = { $Display_name_val.Text = ($First_name_val.Text + "." + $Second_name_val.Text) }
[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave( { & $showFullName } )
#endregion
#region User name of the user
$User_name_lbl = New-Object system.Windows.Forms.Label
$User_name_lbl.text = "User logon name"
$User_name_lbl.AutoSize = $true
$User_name_lbl.width = 25
$User_name_lbl.height = 10
$User_name_lbl.location = New-Object System.Drawing.Point(10,70)
$User_name_val = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline = $false
$User_name_val.width = 250
$User_name_val.height = 20
$User_name_val.location = New-Object System.Drawing.Point(200,70)
$LogonName = {$User_name_val.Text = ($First_name_val.Text + "." + $Second_name_val.Text)}
[void]$Second_name_val.Add_Leave({& $LogonName})
[void]$First_name_val.Add_Leave({& $LogonName})
[void]$AD_user_creation.ResumeLayout()
#endregion
The error "The server is unwilling to process the request" means that some of your input values are invalid. For example, the OU you are providing could be invalid (maybe a space that shouldn't be there), or the SamAccountName might be too long or contain an invalid character, etc.
If you show the full command you are using I might be able to spot something.
If there was an issue connecting to the server or authenticating, then the error message would be different.