I have a script with a userform with which you can edit an ad user object.
The script runs fine directly on our server but when I try to run it from my system with admin privileges, New-PSSession and a few Invoke-Command's the necessary variables are losing their values.
Here's my code (Some stuff has been censored):
#--------------------#
# Function GUI > GUI #
#--------------------#
Function GUI
{
#---Param
[String]$BadgeListCSV = "link" # -> Badge list
[Bool]$UserChk = $False # -> Indicates if the user has been found
[Bool]$BadgeChk = $False # -> Indicates if the badge is already linked with an ad object
[Int]$BadgeIndex = 1 # -> Badge Nr.
#Global variables
Set-Variable -Name Exit -Value $True -Scope Global
#---Importing badge list
Try
{
$BadgeList = Import-CSV $BadgeListCSV
}
Catch
{
DisplayMSGBox -MSGText "Could not access CSV file." -AddErrorInfo $True | Out-Null
LogFileCleanUp
[System.Environment]::Exit(0)
}
ShowWallBoard
#---Form
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(184,197)
$Form.Font = New-Object System.Drawing.Font("Segoe UI",9,0,3,1)
$Form.FormBorderStyle = "FixedSingle"
$Form.MaximizeBox = $False
$Form.Text = "S/R Visitor Badge"
$Form.StartPosition = "CenterScreen"
#---GroupBox Badges
$GBBadges = New-Object System.Windows.Forms.GroupBox
$GBBadges.Location = New-Object System.Drawing.Size(10,5)
$GBBadges.Size = New-Object System.Drawing.Size(158,70)
$GBBadges.Text = "Badge"
#Badge choice
$CBBadgeChoice = New-Object System.Windows.Forms.ComboBox
$CBBadgeChoice.Location = New-Object System.Drawing.Size(10,20)
$CBBadgeChoice.Size = New-Object System.Drawing.Size(110)
$CBBadgeChoice.FlatStyle = "PopUp"
$CBBadgeChoice.DropDownStyle = 2
#---Retrieving badge list
Try
{
ForEach($Badge in $BadgeList)
{
$CBBadgeChoice.Items.Add("Visitor Badge $BadgeIndex") | Out-Null
$BadgeIndex++
}
}
Catch
{
DisplayMSGBox -MSGText "Could generate badge choice combobox." -AddErrorInfo $True | Out-Null
LogFileCleanUp
[System.Environment]::Exit(0)
}
$CBBadgeChoice.SelectedIndex = 0
#Unlink
$ChBUnlink = New-Object System.Windows.Forms.CheckBox
$ChBUnlink.Location = New-Object System.Drawing.Size(10,47)
$ChBUnlink.Size = New-Object System.Drawing.Size(135,18)
$ChBUnlink.FlatStyle = "Flat"
$ChBUnlink.Text = "Unlink this badge"
#PictureBox Badge
$PBBadge = New-Object System.Windows.Forms.PictureBox
$PBBadge.Location = New-Object System.Drawing.Size(130,23)
$PBBadge.Size = New-Object System.Drawing.Size(16,16)
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
#---GroupBox User
$GBUser = New-Object System.Windows.Forms.GroupBox
$GBUser.Location = New-Object System.Drawing.Size(10,77)
$GBUser.Size = New-Object System.Drawing.Size(158,53)
$GBUser.Text = "User"
#UserName
$TBUserName = New-Object System.Windows.Forms.TextBox
$TBUserName.Location = New-Object System.Drawing.Size(10,20)
$TBUserName.Size = New-Object System.Drawing.Size(110)
$TBUserName.BorderStyle = 1
#PictureBox UserName
$PBUserName = New-Object System.Windows.Forms.PictureBox
$PBUserName.Location = New-Object System.Drawing.Size(130,23)
$PBUserName.Size = New-Object System.Drawing.Size(16,16)
$PBUserName.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
#---Buttons
$BValidate = New-Object System.Windows.Forms.Button
$BValidate.Location = New-Object System.Drawing.Size(10,139)
$BValidate.Size = New-Object System.Drawing.Size(75,23)
$BValidate.FlatStyle = "PopUp"
$BValidate.Text = "Validate"
$BConfirm = New-Object System.Windows.Forms.Button
$BConfirm.Location = New-Object System.Drawing.Size(93,139)
$BConfirm.Size = New-Object System.Drawing.Size(75,23)
$BConfirm.FlatStyle = "PopUp"
$BConfirm.Text = "Confirm"
$BConfirm.Enabled = $False
#---Eventhandling
$DisableTextBox=
{
#---"Unlink this badge" is unchecked
if($ChBUnlink.Checked -eq $False)
{
#---Enable texbox
$TBUserName.Enabled = $True
#---Clear textbox
$TBUserName.Text = ""
#---Set both picture boxes to cross.png
$PBBadge.Image = $PBUserName.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
}
#---"Unlink this badge" is checked
if($ChBUnlink.Checked -eq $True)
{
#---Disable textbox
$TBUserName.Enabled = $False
#---Clear textbox
$TBUserName.Text = ""
#---Set the picture box next to the username input textbox to tick.png
$PBUserName.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\tick.PNG")
#---Setting badge check
$BadgeChk = $False
#---Set the picture box next to badge choice combobox to tick.png
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
}
}
#---Buttons On-Click-Actions
$BValidate_OnClick=
{
#---Param
[String]$UserName = $TBUserName.Text # -> Username
[Int]$BadgeCSVID = $CBBadgeChoice.SelectedIndex # -> Index which indicates which badge got selected: Index = 0 -> Visitor Badge 1, Index 1 -> Visitor Badge 2
[Long]$BadgeID = $BadgeList[$BadgeCSVID].ID # -> Getting badge id from csv file
$Form.Enabled = $False
Try
{
#---UserChk
if($UserName -ne "")
{
$UserChk = Invoke-Command -Session $OurADServer -ScriptBlock{Param($UserName) [Bool](Get-ADUser -Filter { sAMAccountName -eq $UserName } -Searchbase "SB")} -ArgumentList $UserName
if($UserChk -eq $False)
{
$PBUserName.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
}
ElseIf($UserChk -eq $True)
{
$PBUserName.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\tick.PNG")
}
}
}
Catch
{
DisplayMSGBox -MSGText "Could not validate the user." -AddErrorInfo $True | Out-Null
LogFileCleanUp
[System.Environment]::Exit(0)
}
Try
{
#---BadgeChk
$BadgeChk = Invoke-Command -Session $OurADServer -ScriptBlock{Param($BadgeID) [Bool](Get-ADObject -Filter { Pager -eq $BadgeID })} -ArgumentList $BadgeID
if($BadgeChk -eq $True)
{
#---Retrieving all linked ad objects
$AllLinkedObjectsArray = New-Object System.Collections.ArrayList
$AllLinkedObjects = Invoke-Command -Session $OurADServer -ScriptBlock{Param($BadgeID) Get-ADObject -Filter { Pager -eq $BadgeID }} -ArgumentList $BadgeID
ForEach($Object in $AllLinkedObjects)
{
$AllLinkedObjectsArray.Add($Object.Name) | Out-Null
}
#---Joins array into string with breaks
$AllLinkedObjectsString = $AllLinkedObjectsArray -Join "
"
if($ChBUnlink.Checked -eq $False)
{
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
if((DisplayMSGBox -MSGText ($CBBadgeChoice.SelectedItem + " is already linked with the following objects:`n`n$AllLinkedObjectsString`n`nDo you wish to clear these links?”) -MSGButtons YesNo -MSGIcon Question) -eq "Yes")
{
ReleaseVisitorBadge $AllLinkedObjectsString $BadgeCSVID $BadgeID
}
}
elseif($ChBUnlink.Checked -eq $True)
{
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\tick.PNG")
}
}
elseif($BadgeChk -eq $False)
{
if($ChBUnlink.Checked -eq $False)
{
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\tick.PNG")
}
elseif($ChBUnlink.Checked -eq $True)
{
$PBBadge.Image = [System.Drawing.Image]::FromFile("$ScriptPath\images\cross.PNG")
DisplayMSGBox -MSGText ($CBBadgeChoice.SelectedItem + " is currently not in use.") -MSGIcon Information | Out-Null
}
}
}
Catch
{
DisplayMSGBox -MSGText "Could not validate the badge." -AddErrorInfo $True | Out-Null
LogFileCleanUp
[System.Environment]::Exit(0)
}
$Form.Enabled = $True
#---Enabling / disabling the button "Confirm"
if(($BadgeChk -eq $False -and $UserChk -eq $True) -or ($BadgeChk -eq $True -and $ChBUnlink.Checked -eq $True))
{
$BConfirm.Enabled = $True
}
else
{
$BConfirm.Enabled = $False
}
}
$BConfirm_OnClick=
{
if($BadgeChk -eq $False -and $UserChk -eq $True)
{
Set-Variable -Name Exit -Value $False -Scope Global
$Form.Close()
SetVisitorBadge $UserName $BadgeCSVID $BadgeID
}
ElseIf($BadgeChk -eq $True -and $ChBUnlink.Checked -eq $True)
{
Set-Variable -Name Exit -Value $False -Scope Global
$Form.Close()
ReleaseVisitorBadge $AllLinkedObjectsString $BadgeCSVID $BadgeID
}
}
#---Adding Elements to the form
$BValidate.Add_Click($BValidate_OnClick)
$BConfirm.Add_Click($BConfirm_OnClick)
$ChBUnlink.Add_CheckedChanged($DisableTextBox)
$Form.Add_Shown({$Form.Activate(); $TBUserName.Focus()})
$GBBadges.Controls.Add($CBBadgeChoice)
$GBBadges.Controls.Add($PBBadge)
$GBBadges.Controls.Add($ChBUnlink)
$GBUser.Controls.Add($TBUserName)
$GBUser.Controls.Add($PBUserName)
$Form.Controls.Add($GBBadges)
$Form.Controls.Add($GBUser)
$Form.Controls.Add($BValidate)
$Form.Controls.Add($BConfirm)
$Form.ShowDialog()| Out-Null
}
I have two options in my userform. After the user has entered the data, he has to validate it by clicking on "Validate". If everything is correct, the button "Confirm" gets activated and the AD user object may be changed.
However, after validating the data and then clicking on "Confirm" all necessary variables lost their values and I don't know why.
As you can see below, everything is set after validating the data but when I try to confirm it, all values are gone.
The script worked just fine as it is now when run directly on our AD server. All I did was trying to run it via my system by adding a remote session and Invoke-Command's. Could this really be an issue here?
Thanks for any help.
Related
my script is trying to check if you entered a computer neme
$credObjects = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userNames, $passwords
$Credential = Get-Credential -Credential $credObjects
$Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher
$searcher = [adsisearcher]"(&(objectCategory=computer)(objectClass=computer)(name=$global:NewComputerName))"
$searcher.PropertiesToLoad.AddRange(('name'))
$searchResult = $searcher.FindAll()
if($searchResult.count -eq 1)
{
$Result = $true
}
else
{
$Result = $False
}
and them use it in if statement to popup message
elseif ($Result -match 'true')
{
$msgBoxInput7 = [System.Windows.Forms.MessageBox]::Show('computer is exist', 'OK')
switch ($msgBoxInput7) {
'OK' {
$groupbox1.ResumeLayout()
$form1.ResumeLayout()
$form1.add_FormClosed($Form_Cleanup_FormClosed)
}
}
}
any help to make it work
the code is working fine if i run script in admin in powershell
but when run it as user not working as expected
Following on from a previous question
The actual code is a lot more complex, but the following is working example of my loop:
Add-Type -AssemblyName System.Windows.Forms
$source = '\\servera\files'
$destination = '\\server b\files'
$form = New-Object System.Windows.Forms.Form
$CopyOutput = New-Object System.Windows.Forms.Label
$CopyOutput.Location = '10,15'
$CopyOutput.Size = '350,20'
$form.Text = "$DomainName Folder/Archive Copy"
$form.Size = '380,130'
$form.CancelButton = $ExitButton
$form.Add_FormClosing({
$script:CancelLoop = $true
})
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Name = 'StartButton'
$StartButton.Location = '10,50'
$StartButton.Size = '75,23'
$StartButton.Text = 'Start Copy'
$StartButton.Enabled = $true
$PauseButton = New-Object System.Windows.Forms.Button
$PauseButton.Location = '100,50'
$PauseButton.Size = '75,23'
$PauseButton.Text = 'Pause Copy'
$PauseButton.Enabled = $true
$StopButton = New-Object System.Windows.Forms.Button
$StopButton.Location = '190,50'
$StopButton.Size = '75,23'
$StopButton.Text = 'Stop Copy'
$StopButton.Enabled = $true
$ExitButton = New-Object System.Windows.Forms.Button
$ExitButton.Name = 'ExitButton'
$ExitButton.Location = '280,50'
$ExitButton.Size = '75,23'
$ExitButton.Text = 'Exit'
$ExitButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.Controls.AddRange(#($StartButton,$PauseButton,$StopButton,$ExitButton,$CopyOutput))
$StopButton.Add_Click({
$script:PauseToggle = $false
$script:CancelLoop = $true
})
$PauseButton.Add_Click({
# Boolean change value to true/false
$script:PauseToggle = !$script:PauseToggle
})
$StartButton.Add_Click({
$script:CancelLoop = $false
$script:PauseToggle = $false
$StopButton.Enabled = $true
$StartButton.Enabled = $false
Get-ChildItem -LiteralPath $Source -Recurse -File | ForEach {
Copy-Item -LiteralPath $_.FullName -Destination $Destination
$CopyOutput.Text = ('Copying' + $_.FullName)
[System.Windows.Forms.Application]::DoEvents()
If($script:CancelLoop -eq $true) {
$CopyOutput.Text = 'Cancel copy'
#Exit the loop
Break;
}
If ($script:PauseToggle) {
$CopyOutput.Text = 'Paused'
Do {
[System.Windows.Forms.Application]::DoEvents()
} Until (!$script:PauseToggle)
}
}
$CancelButton.Enabled = $false
$StartCopyButton.Enabled = $true
})
$form.ShowDialog()
$form.Dispose()
All the articles I can find say that this code should work ok - can anyone advise how to avoid the unhandled exception which results when the "Stop" button is pressed?
All the articles I can find say that this code should work ok - can anyone advise how to avoid the unhandled exception which results when the "Stop" button is pressed?
From what I can see in my research, this is an issue with using BREAK in forms. I did however find a workaround from here
Using this commandlet will stop the current pipeline instead of using BREAK
Filter Stop-Pipeline {
$sp = { Select-Object -First 1 }.GetSteppablePipeline($MyInvocation.CommandOrigin)
$sp.Begin($true)
$sp.Process(0)
}
The script included is to check the replication and repair for each Server that I add. The goal I have in mind is for it to automatically check the connection of each computer as I add them as well as check the uptime.
The current issue I'm having is that it will delay to check the uptime before it allows me to input my next computer.
As you can see in my script I'm trying to use a start-job which is not working at all for me as it says the 'ComputerName' is null, but the ComputerName is set in the Get-Uptime function.
I may be going about this all wrong. Any help would be great!!
function Check-Replication {
#----------------------------------------------
#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
$base64Image = "iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAQAAADYWf5HAAAABGdBTUEAALGPC/xhBQAAAAJiS0dEAP+Hj8y/AAAACXBIWXMAAWG3AAFhtwFW7IyrAAAAB3RJTUUH4goDDxY48JvtEgAAAg9JREFUKM9NkT9MU1EUxn/33kf/APVPYQGaYImLYQAikU6kidFoWBwYjLgw6SZxkLhgnExc0A1ZHDC6uOmMDQ5KLCYuqINxoFgq2Ce0fbx/912GvhDOlzN9X77znXMEAFyhL7Uxmbl9vjjQn1ahrv35Vdp7NbxWc1eJaxFJIX9h+UZ9yZTMF/PVlM1Hs2Jm6yPLl/KwCIinPGZwxHsxPnGTXhQSgSEi4oB3rK7LO1vfFlA75Ib2X54rTJNFIBGAISLE0MdOrjo69GHDlteT9nxXYZQMEWBOQNPBGJmCPX81qZzL/kIuPUwPHVjxSIiI0Pj4/MXOV8pWa6Yzm0XFhIzXimLAGTqzrRkrKnbThSYgxELEwoiQkJCATrppFi09kCKJwSNJgEEgMBhCAjwCEqTQA5ZW7SME+AiiE24BPgaJQiuptI5zaCLMcRs0bSZEaSm3D/HwCdBodCzS6Dibh4valrLUoEGLQ1x8guPoPh6HODRpQkkNOs5UIp0mgUIAEZoQH5cm+/yjym6965GarXwfdC8msOJfhrFPW1Sjgl65tqRsfXrz/4SXkxg0IR4uDg322aPGFo3PPfc399QD3ti95dZYKxfg4+LQ4gCbXapUaKwn7/78MYeA59yjkK8/NNPpsxlSKDQuTRxbvs0++fT7GXOI9g+n6E+VJw9umaLJhcrSoiJKp16Pr1Xd9wAcAYNiEWcBi781AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE4LTEwLTAzVDE1OjIyOjU2LTA0OjAwISeC9gAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxOC0xMC0wM1QxNToyMjo1Ni0wNDowMFB6OkoAAAAASUVORK5CYII="
$imageBytes = [Convert]::FromBase64String($base64Image)
$memStream = New-Object IO.MemoryStream($imageBytes, 0, $imageBytes.Length)
$memStream.Write($imageBytes, 0, $imageBytes.Length);
$imageGrey = [System.Drawing.Bitmap]::FromStream($memStream, $true)
$base64Image = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH4goDDxstKOh3tAAABJVJREFUOMtVlNtvVFUUxn/r3M8w7bSddloYWkpALlqoEBJ9IIQoSUUTEYj6B8CLMSbySOKTvtQYnlDf1ITggwHFiEAIl4CVxPBAAhQKIVwCpXTaTjuXM3PmXOZsH6aA7uTbe2Vl5Vt7rXxrCf85V69epVKpkMvlejVNW2saZtq2HU3XdA+gmcRdYRRKGIalJEkm6vX6M8uy1ObNm19wyHPj2rVrJEliua671bGdnFetPbwwdm7g1v3xVTPFmXbTMLUlqXRheM3wo5HtI0U3neoJgqAahuGYpmn+8PDwS8Lx8XGSJGlzHPtz07SWnT5/ev63yye2VbTqJiujp6wlpogIoR+rZjXxcnbvnd1bd13Z/uZ2I4zDsu/7h3RdXxgaGkKuX79Oo9EwM5n2L0zD+uT4mWP1Hy791FfL1my1VBGkAiIjBAEjNnHqDvqMTrbWGe/fvr/47rb39DAKf/Y876Bpmr5hGAau6+7WNf3T38+e0L85e2h5qb+kq/6EZrYJ7SB2qzMqBKoK3dF5NjlljJ79utc0zOCtN97eZ9nWDdd1fzR83+9LuakDE/fuZL87972aWzYrskpQeZBuDdIKLEAJEivwhKRdoeyEyeYk354/bK/Mr7SX9/Z/Vi6VL2oi8m4QhJuOXfiVh9YjkRUtMpYCvQp6gRyQU5AD1QcsVUgeZFC4pSb4458/iaJoSET2akqpXZNTj+0rD/9G9SXQI0g3SBeoTlDtQBuojEAGJAN0AVmgB5KehL8eXGa2OGskSfK+EUfx6/cfP6DQfIZ0AG0K0kAaJAU4gC6AAmNRY3ErCW2tJE8LT5mcfUrKTW3U6vV6R6FYIDBDcARsWj0zQAxpkT2HAZiAqVAmYCtwFL40KJaL+HU/ozUaDYmiCEFQAiIvJ0ct3uqF9XIe5LlDtcQcxTG+74vWTJrltJPGbtrQWJRG1CpLxQrVBEkUkihoKogXEQEhSAAOLq7h0Gw2K5pK1I2u9i5yeg7KIFXAE1Qd8IEGECyiAcoHaoKqAR6oMuTtPGkrTaKSW5ph6KeWpNqjDd0b0GcENStQBJkHKYFUgEVIGaQksNCKUXOgF3U29W1GFz0xDOOUls12n7Rt8+aWFVsYjAZRTxLUlIJpoADMPoe03gIwrWAKeKxYr69nY+8QmsjdTCZzXM/n85XBFSuCZpS80yEdxuPJJ9TCKpIIhK2yVX3xp0VgRmAK5KGivzTAx2s+JJvqjjq7Or86evToGX10dJSBgYG7Cwvz3SbmlqVmn3hzVYJKiBEYaDUdKYFWFIw5E6dg4046rA3W8MGqPfSlelVHR8eRda+uGx3eOBwKwKVLl2hra+u6ffv2l4Xpwr6F6rxzv/SAp/EkDScAp6UPLdBwohT97gCr21eRttJRNps9svqV1Qc9z5vduXPnywU7NjZGJpNxb9y8+dH83NyBeq021IgC3U8CYmJEwBILx3AxdbPpOs69bHf28Lq1646Uy2Vvx44d/9/YAIVCgVwux4WLFwann03v9TxvTxAEr8VxnBEEXdcrlmVNpNvSJ3t6en4ZGRm5PzU1pfL5/AuOfwFWfAyFldyKLAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOC0xMC0wM1QxNToyNzo0NS0wNDowMDpMU7EAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTgtMTAtMDNUMTU6Mjc6NDUtMDQ6MDBLEesNAAAAAElFTkSuQmCC"
$imageBytes = [Convert]::FromBase64String($base64Image)
$memStream = New-Object IO.MemoryStream($imageBytes, 0, $imageBytes.Length)
$memStream.Write($imageBytes, 0, $imageBytes.Length);
$imageGreen = [System.Drawing.Bitmap]::FromStream($memStream, $true)
$base64Image = "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"
$imageBytes = [Convert]::FromBase64String($base64Image)
$memStream = New-Object IO.MemoryStream($imageBytes, 0, $imageBytes.Length)
$memStream.Write($imageBytes, 0, $imageBytes.Length);
$imageRed = [System.Drawing.Bitmap]::FromStream($memStream, $true)
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$labelTypeEachComputerName = New-Object 'System.Windows.Forms.Label'
$textbox1 = New-Object 'System.Windows.Forms.TextBox'
$datagridview1 = New-Object 'System.Windows.Forms.DataGridView'
$buttonRun = New-Object 'System.Windows.Forms.Button'
$Online = New-Object 'System.Windows.Forms.DataGridViewImageColumn'
$Uptime = New-Object 'System.Windows.Forms.DataGridViewTextBoxColumn'
$Computer = New-Object 'System.Windows.Forms.DataGridViewTextBoxColumn'
$Status = New-Object 'System.Windows.Forms.DataGridViewTextBoxColumn'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# Function Get-Uptime
#----------------------------------------------
#region - Get-Uptime
$Uptime1 = {
function Get-Uptime {
Params ($ComputerName)
$global:ComputerName = $row.cells[2].Value
$os = Get-WmiObject win32_operatingsystem -ComputerName $ComputerName -ErrorAction SilentlyContinue
if ($os.LastBootUpTime) {
$uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
#Write-Output ("Last boot: " + $os.ConvertToDateTime($os.LastBootUpTime) )
Write-Output ("" + $uptime.Days + "d " + $uptime.Hours + "h " + $uptime.Minutes + "m" )
} else {
Write-Warning "Unable to connect to $computername"
}
}
}
#endregion
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$FormEvent_Load = {
}
$textbox1_Validated = {
if ($textbox1.Text -ne "") {
$i = $datagridview1.Rows.Add(1)
$row = $datagridview1.Rows[$i]
$row.SetValues(#($imageGrey,'',$textbox1.Text,'pending'))
$textbox1.Text = ''
$textbox1.Focus()
if ($row.Cells[2].Value -ne "") {
if (Test-Connection -ComputerName $row.cells[2].Value -Count 1 -Quiet) {
$Time = Get-Date
Start-Job -InitializationScript $Uptime1 -scriptblock {(Get-Uptime -ComputerName $args[0])} -Args $row.cells[2].Value |
#Start-Job -InitializationScript $Uptime1 -scriptblock {(Get-Uptime)}|
Wait-Job | Receive-Job
$row.SetValues(#($imageGrey,($Uptime),$row.Cells[2].Value))
#Remove-Job -Name CheckSiteUptime
$Time = Get-date
$row.Cells[0].Value = $imageGreen
} else {
$row.Cells[0].Value = $imageRed}
}
}
}
$buttonRun_Click = {
$datagridview1.Rows | ForEach-Object {
$row = [System.Windows.Forms.DataGridViewRow]$_
$CommandResult = Invoke-Command -ComputerName $row.cells[2].Value -ArgumentList $row -ScriptBlock{
Param($row)
Import-Module Hyper-V
if ((Get-VM -ErrorAction Stop | Where-Object {$_.name -like '*SR*'} | Get-VMReplication -ErrorAction Stop).Replicationhealth -eq 'critical') {
try{
Get-VM -ErrorAction Stop | Where-Object {$_.name -like '*SR*'} | Resume-VMReplication -ErrorAction Stop
if ((Get-VM -ErrorAction Stop | Where-Object {$_.name -like '*SR*'} | Get-VMReplication -ErrorAction Stop).Replicationhealth -eq 'critical') {
throw [System.Exception] "Replicationhealth critical"
}
} catch {
try{
Get-VM -ErrorAction Stop | Where-Object {$_.name -like '*SR*'} | Resume-VMReplication -Resynchronize -ErrorAction Stop
} catch {
return 'FAILED: Resume-VMReplication -Resynchronize'
break
}
return 'Successful: Resume-VMReplication -Resynchronize'
break
}
return 'Successful: Resume-VMReplication'
} else {
return 'Successful: No action replication is NOT critical'
}
}
switch ($CommandResult) {
"FAILED: Resume-VMReplication -Resynchronize" {
$row.Cells | %{$_.Style.BackColor = 'pink'}
$Row.Cells[3].Value = $CommandResult
}
"Successful: Resume-VMReplication -Resynchronize" {
$row.Cells | %{$_.Style.BackColor = 'lightgreen'}
$Row.Cells[3].Value = $CommandResult
}
"Successful: Resume-VMReplication" {
$row.Cells | %{$_.Style.BackColor = 'lightgreen'}
$Row.Cells[3].Value = $CommandResult
}
"Successful: No action replication is NOT critical" {
$row.Cells | %{$_.Style.BackColor = 'lightgreen'}
$Row.Cells[3].Value = $CommandResult
}
}
}
$datagridview1.ReadOnly = $true
}
# --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 {
$textbox1.remove_Validated($textbox1_Validated)
$buttonRun.remove_Click($buttonRun_Click)
$form1.remove_Load($FormEvent_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
} catch {
Out-Null <# Prevent PSScriptAnalyzer warning #>
}
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($labelTypeEachComputerName)
$form1.Controls.Add($textbox1)
$form1.Controls.Add($datagridview1)
$form1.Controls.Add($buttonRun)
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '625, 600'
$form1.FormBorderStyle = 'FixedDialog'
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
$form1.Name = 'form1'
$form1.StartPosition = 'CenterScreen'
$form1.Text = 'Replication Check'
$form1.add_Load($FormEvent_Load)
#
# labelTypeEachComputerName
#
$labelTypeEachComputerName.Location = '20, 18'
$labelTypeEachComputerName.Name = 'labelTypeEachComputerName'
$labelTypeEachComputerName.Size = '240, 49'
#$labelTypeEachComputerName.TabIndex = 5
$labelTypeEachComputerName.Text = 'Type each computer name ending with a <tab> it will be added to the list. Click run when alll have been added.'
$labelTypeEachComputerName.UseCompatibleTextRendering = $True
#
# textbox1
#
$textbox1.CharacterCasing = 'Upper'
$textbox1.Location = '20, 81'
$textbox1.Name = 'textbox1'
$textbox1.Size = '285, 20'
#$textbox1.TabIndex = 1
$textbox1.add_Validated($textbox1_Validated)
#
# datagridview1
#
$datagridview1.AllowUserToAddRows = $False
$datagridview1.AllowUserToDeleteRows = $False
$datagridview1.AllowUserToResizeColumns = $True
$datagridview1.AllowUserToResizeRows = $False
$datagridview1.ColumnHeadersHeightSizeMode = 'AutoSize'
[void]$datagridview1.Columns.Add($Online)
[void]$datagridview1.Columns.Add($Uptime)
[void]$datagridview1.Columns.Add($Computer)
[void]$datagridview1.Columns.Add($Status)
$datagridview1.columns[0].Width = '40'
$datagridview1.columns[3].Width = '250'
$datagridview1.Location = '20, 113'
$datagridview1.Name = 'datagridview1'
$datagridview1.ReadOnly = $True
$datagridview1.Size = '583, 470'
$datagridview1.TabIndex = 3
$datagridview1.DefaultCellStyle.WrapMode = "True"
#
# buttonRun
#
$buttonRun.Location = '325, 80'
$buttonRun.Name = 'buttonRun'
$buttonRun.Size = '75, 23'
$buttonRun.TabIndex = 2
$buttonRun.TabStop = $False
$buttonRun.Text = 'Run'
$buttonRun.UseCompatibleTextRendering = $True
$buttonRun.UseVisualStyleBackColor = $True
$buttonRun.add_Click($buttonRun_Click)
#
# Online
#
$Online.HeaderText = 'Online'
$Online.Name = 'Online'
$Online.DataPropertyName = 'Online'
#
# Uptime
#
$Uptime.HeaderText = 'Uptime'
$Uptime.Name = 'Uptime'
$Uptime.ReadOnly = $True
#
# Computer
#
$Computer.HeaderText = 'Server'
$Computer.Name = 'Server'
$Computer.ReadOnly = $True
#
# Status
#
$Status.HeaderText = 'Status'
$Status.Name = 'Status'
$Status.ReadOnly = $True
$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
Check-Replication | Out-Null
Because PowerShell jobs run in a separate runspace, even declaring a variable as $global: does not make it available inside your job. Instead, you need to pass the value in to your job when you create it.
For example, you could change your code as follows:
...
Function Get-Uptime {
params ($ComputerName)
$global:ComputerName = $ComputerName
...
Start-Job -InitializationScript $Uptime1 -scriptblock {(Get-Uptime -ComputerName $args[0])} -Args $row.cells[2].Value
A similar issue is described here: https://social.technet.microsoft.com/Forums/ie/en-US/5b369c15-d2ad-4ee8-a1fc-3f0ca8df230a/powershell-jobs-and-global-variables?forum=ITCG
Another resource on some options other than PS jobs, which tend to be relatively inefficient: https://randombrainworks.com/2018/01/28/powershell-background-jobs-runspace-jobs-thread-jobs/
Another way around your base issue of de-coupling your form/GUI from your backend code is to use runspaces and a synchronized hashtable. The advantage of this model is that your can have many threads simultaneously performing work and actively updating your form, and instead of passing variables around, you have a single copy and pass references.
This is a great article to get started: https://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/
I am trying to write a script which displays Active Directory users which are expired and disabled in a listview. I want the listview to group the accounts by disabled and expired accounts. When I run the script in the ISE, it displays properly:
When I run the script in a normal PowerShell prompt, grouping doesn't work:
I'm running PowerShell 5 on Windows 10 1703. This is my code, what have I done wrong?
Function ViewAllInactiveUsers {
$ViewAllInactiveUsersForm = New-Object system.Windows.Forms.Form
$ViewAllInactiveUsersForm.Text = "View All Inactive Users"
$ViewAllInactiveUsersForm.TopMost = $false
$ViewAllInactiveUsersForm.Width = 900
$ViewAllInactiveUsersForm.Height = 700
$ViewAllInactiveUsersForm.MinimizeBox = $false
$ViewAllInactiveUsersForm.MaximizeBox = $false
$ViewAllInactiveUsersForm.FormBorderStyle = "FixedDialog"
$InactiveListView_DoubleClick={
$InactiveUserTextBox.text = $InactiveListView.SelectedItems[0].SubItems[0].Text
}
#Define Header
$InactiveImage1 = [System.Drawing.Image]::FromFile("c:\Users\i.north\Documents\CWP\habs.png")
$InactiveImage = New-Object System.Windows.Forms.PictureBox
$InactiveImage.Width = $InactiveImage1.Size.Width
$InactiveImage.Height = $InactiveImage1.Size.Height
$InactiveImage.location = New-Object System.Drawing.Size(20,0)
$InactiveImage.image = $InactiveImage1
$ViewAllInactiveUsersForm.Controls.Add($InactiveImage)
$InactiveTitleFont = New-Object System.Drawing.Font("Calibri",20,[System.drawing.fontstyle]::Regular)
$InactiveTitleText = New-Object System.Windows.Forms.Label
$InactiveTitleText.Font = $TitleFont
$InactiveTitleText.Text = "View All Inactive Guests"
$InactiveTitleText.Location = New-Object System.Drawing.Size(330,20)
$InactiveTitleText.Size = New-Object System.Drawing.Size(400,100)
$ViewAllInactiveUsersForm.Controls.Add($InactiveTitleText)
#List box with Inactive users in
$InactiveListView = New-Object system.windows.Forms.ListView
$InactiveListView.Width = 840
$InactiveListView.Height = 300
$InactiveListView.location = new-object system.drawing.point(20,139)
$InactiveListView.View = [System.Windows.Forms.View]::Details
$InactiveListView.HeaderStyle = "nonclickable"
$InactiveListView.FullRowSelect = $true
$InactiveListView.add_SelectedIndexChanged({
If ($InactiveListView.Items.Count -gt 0)
{
$InactiveExtendButton.Enabled = $true
$InactiveDisableButton.Enabled = $true
$InactiveResetButton.Enabled = $true
$InactiveUserTextBox.Enabled = $true
$InactiveDurationBox.Enabled = $true
$InactiveUserTextBox.BackColor = "#ffffff"
}
Else
{
$InactiveExtendButton.Enabled = $false
$InactiveDisableButton.Enabled = $false
$InactiveResetButton.Enabled = $false
}
})
$InactiveListView.add_Click({$InactiveUserTextBox.text = $InactiveListView.SelectedItems[0].SubItems[0].Text})
$ViewAllInactiveUsersForm.controls.Add($InactiveListView)
$InactiveListView.Columns.Add("Guest User Name", -2)
$InactiveListView.Columns.Add("Guest Forename", -2)
$InactiveListView.Columns.Add("Guest Surname", -2)
$InactiveListView.Columns.Add("Guest Company", 250)
$InactiveListView.Columns.Add("Guest Sponsor", -2)
$InactiveListView.Columns.Add("Account Status", -2 )
$InactiveListView.Columns.Add("Account Expiry Time", -2)
$InactiveListViewDisabledGroup = New-Object System.Windows.Forms.ListViewGroup
$InactiveListViewDisabledGroup.Header = "Disabled Accounts"
$InactiveListView.Groups.Add($InactiveListViewDisabledGroup)
$InactiveListViewExpiredGroup = New-Object System.Windows.Forms.ListViewGroup
$InactiveListViewExpiredGroup.Header = "Expired Accounts"
$InactiveListView.Groups.Add($InactiveListViewExpiredGroup)
$InactiveListView.ShowGroups = $true
#Get all Inactive guest AD users and put them into the list view
$GuestUsersExpired = get-aduser -filter {enabled -eq $true} -searchbase "ou=Guest Wifi Users,ou=Guest Wifi,dc=hahc,dc=internal" -Properties displayname,company,mail,officephone,description,office,accountexpires,AccountExpirationDate | Where-Object { $_.AccountExpirationDate -ne $null -and $_.AccountExpirationDate -lt (Get-Date) }
$GuestUsersExpired | ForEach-Object {
$Sponsor = $_.description
$SponsorSplit = $Sponsor.IndexOf("-")
$InactiveListViewItem = New-Object System.Windows.Forms.ListViewItem($_.SamAccountName)
$InactiveListViewItem.SubItems.Add($_.GivenName)
$InactiveListViewItem.SubItems.Add($_.Surname)
$InactiveListViewItem.SubItems.Add($_.Company)
$InactiveListViewItem.SubItems.Add($Sponsor.substring($SponsorSplit+2))
$InactiveListViewItem.SubItems.Add("Expired")
$InactiveListViewItem.SubItems.Add("$(Get-Date([datetime]::FromFileTime($_.AccountExpires)) -Format "ddd d MMM yyyy, HH:mm")")
$InactiveListViewItem.Group = $InactiveListViewExpiredGroup
$InactiveListView.Items.Add($InactiveListViewItem)
}
$GuestUsersDisabled = get-aduser -filter {enabled -eq $false} -searchbase "ou=Guest Wifi Users,ou=Guest Wifi,dc=hahc,dc=internal" -Properties displayname,company,mail,officephone,description,office,accountexpires,AccountExpirationDate
$GuestUsersDisabled | ForEach-Object {
$Sponsor = $_.description
$SponsorSplit = $Sponsor.IndexOf("-")
$InactiveListViewItem = New-Object System.Windows.Forms.ListViewItem($_.SamAccountName)
$InactiveListViewItem.SubItems.Add($_.GivenName)
$InactiveListViewItem.SubItems.Add($_.Surname)
$InactiveListViewItem.SubItems.Add($_.Company)
$InactiveListViewItem.SubItems.Add($Sponsor.substring($SponsorSplit+2))
$InactiveListViewItem.SubItems.Add("Disabled")
$InactiveListViewItem.SubItems.Add("$(Get-Date([datetime]::FromFileTime($_.AccountExpires)) -Format "ddd d MMM yyyy, HH:mm")")
$InactiveListViewItem.Group = $InactiveListViewDisabledGroup
$InactiveListView.Items.Add($InactiveListViewItem)
}
#Extend/Reset/Delete User area
#Put it all into a groupbox, make it look a little neater
$InactiveUserAreaGroupBox = New-Object System.Windows.Forms.GroupBox
$InactiveUserAreaGroupBox.Location = New-Object System.Drawing.Size(20,460)
$InactiveUserAreaGroupBox.Height = 135
$InactiveUserAreaGroupBox.Width = 840
$InactiveUserAreaGroupBox.Text = "User Control Area"
$ViewAllInactiveUsersForm.Controls.Add($InactiveUserAreaGroupBox)
#Label
$InactiveUserLabel = New-Object System.Windows.Forms.Label
$InactiveUserLabel.Location = New-Object System.Drawing.Size(20,20)
$InactiveUserLabel.Size = New-Object System.Drawing.Size(110,50)
$InactiveUserLabel.Text = "Guest UserName"
$InactiveUserAreaGroupBox.Controls.Add($InactiveUserLabel)
#TextBox
$InactiveUserTextBox = New-Object System.Windows.Forms.TextBox
$InactiveUserTextBox.Location = New-Object System.Drawing.Size(130,20)
$InactiveUserTextBox.Size = New-Object System.Drawing.Size(200,50)
$InactiveUserTextBox.Enabled = $false
$InactiveUserTextBox.ReadOnly = $true
$InactiveUserAreaGroupBox.Controls.Add($InactiveUserTextBox)
#disable user button
$InactiveDisableButton = New-Object System.Windows.Forms.Button
$InactiveDisableButton.Text = "Disable Guest Account"
$InactiveDisableButton.Width = 150
$InactiveDisableButton.Height = 40
$InactiveDisableButton.Location = New-Object System.Drawing.Point(670,70)
$InactiveDisableButton.Enabled = $false
$InactiveDisableButton.add_click({
Get-ADUser -Filter {name -eq $InactiveUserTextBox.Text} | Set-ADUser -Enabled $false
[System.Windows.Forms.MessageBox]::Show("User $($InactiveUserTextBox.Text) has been disabled")
$InactiveListView.Items.Remove($InactiveListView.SelectedItems[0])
})
$InactiveUserAreaGroupBox.Controls.Add($InactiveDisableButton)
#reset password button
$InactiveResetButton = New-Object System.Windows.Forms.Button
$InactiveResetButton.Text = "Reset Guest Password"
$InactiveResetButton.Width = 150
$InactiveResetButton.Height = 40
$InactiveResetButton.Location = New-Object System.Drawing.Point(505,70)
$InactiveResetButton.Enabled = $false
$InactiveResetButton.add_click({
$Password = GenerateRandomishPassword
$PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
$UserToCreate = $InactiveUserTextBox.Text
Get-ADUser -Filter {name -eq $InactiveUserTextBox.Text } | Set-ADAccountPassword -NewPassword $PasswordSecure
UserCreationResultsForm
})
$InactiveUserAreaGroupBox.Controls.Add($InactiveResetButton)
#extend combobox
$InactiveDurationLabel = New-Object System.Windows.Forms.Label
$InactiveDurationLabel.Location = New-Object System.Drawing.Size(340,20)
$InactiveDurationLabel.Size = New-Object System.Drawing.Size(150,40)
$InactiveDurationLabel.Text = "Change Expiry Time to this amount of time from now:"
$InactiveUserAreaGroupBox.Controls.Add($InactiveDurationLabel)
$InactiveDurationBox = New-Object System.Windows.Forms.ComboBox
$InactiveDurationBox.Location = New-Object System.Drawing.Size(505,20)
$InactiveDurationBox.Size = New-Object System.Drawing.Size(150,40)
$InactiveDurationBox.Text = "8 Hours"
$InactiveDurationBox.Enabled = $false
$InactiveDurationBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$InactiveUserAreaGroupBox.Controls.Add($InactiveDurationBox)
$InactiveDurationOptions=#("1 Hour","4 Hours","8 Hours","1 Day","1 Week","1 Month")
Foreach ($InactiveDuration in $InactiveDurationOptions) {
[void] $InactiveDurationBox.items.add($InactiveDuration)
}
#extend button
$InactiveExtendButton = New-Object System.Windows.Forms.Button
$InactiveExtendButton.Text = "Extend Guest Account Expiry Time"
$InactiveExtendButton.Width = 150
$InactiveExtendButton.Height = 40
$InactiveExtendButton.Location = New-Object System.Drawing.Point(670,20)
$InactiveExtendButton.Enabled = $false
$InactiveExtendButton.add_click({
$DurationExpiryTime = $InactiveDurationBox.Text
switch ($DurationExpiryTime) {
"1 Hour" { $TS = New-TimeSpan -Hours 1 }
"4 Hours" { $TS = New-TimeSpan -Hours 4 }
"8 Hours" { $TS = New-TimeSpan -Hours 8 }
"1 Day" { $TS = New-TimeSpan -Days 1 }
"1 Week" { $TS = New-TimeSpan -Days 7 }
"1 Month" { $TS = New-TimeSpan -Days 28 }
Default { $TS = New-TimeSpan -hours 8 }
}
Get-ADUser -filter {name -eq $InactiveUserTextBox.Text } | Set-ADAccountExpiration -TimeSpan $TS
[System.Windows.Forms.MessageBox]::Show("Expiration extended by $($InactiveDurationBox.Text)")
})
$InactiveUserAreaGroupBox.Controls.Add($InactiveExtendButton)
#end of groupbox, everything outside of there now
#Close Button
$InactiveClose = New-Object system.windows.Forms.Button
$InactiveClose.Text = "Close"
$InactiveClose.Width = 150
$InactiveClose.Height = 40
$InactiveClose.location = new-object system.drawing.point(710,600)
$InactiveClose.Add_Click({$ViewAllInactiveUsersForm.close()})
$ViewAllInactiveUsersForm.controls.Add($InactiveClose)
#Activate Form
$ViewAllInactiveUsersForm.Add_Shown({$ViewAllInactiveUsersForm.activate()})
[void] $ViewAllInactiveUsersForm.ShowDialog()
}
ViewAllInactiveUsers
If you closely to the layout you will see more differences between the controls (such as shadows).
I believe your issue is caused by the fact that under the ISE Visual Styles are enabled by default. See: Windows Forms look different in PowerShell and Powershell ISE. Why?
So, I guess the solution is to set [Windows.Forms.Application]::EnableVisualStyles() in your cmdlet.
There is a script on powershell, that creates and removes vpn connection from the user.
The script is a simple form with two buttons "Create" and "Delete", and the output textbox.
If i run a script and click create, the connection is created. But if not closing the form, press delete, the connection is not removed. If i reopen the form, then everything works and connection delete
What could be the problem?
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Windows.Forms.Application]::EnableVisualStyles()
#################Main Form#################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(552,654)
$form.MaximizeBox = $false
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = 'Fixed3D'
$Form.Text = "VPN create"
##########Constants and Variables##########
$IpAddress = #("172.17.0.0/16", "192.168.197.0/24", "192.168.196.0/24")
$vpnConnection = Get-VpnConnection -AllUserConnection
#########Start functions############
function CreateVPN {
if ($vpnConnection.Name -eq "ConWork") {
$outputBox.Text = "connection is already there"
} else {
Add-VpnConnection -Name "ConWork" -ServerAddress "xxx.xxx.xxx.xxx" -TunnelType IKEv2 -EncryptionLevel Required -AuthenticationMethod Eap -SplitTunneling -RememberCredential -AllUserConnection | Out-String
$outputBox.Text += ("Connection created")
$outputBox.Text += "`r`n"
$outputBox.Text += "Routes added"
foreach ($ip in $IpAddress) {
$outputBox.Text += Add-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
}
}
function RemoveVPN {
if ($vpnConnection.Name -eq "ConWork") {
$outputBox.Text += ("Routes delete")
foreach ($ip in $IpAddress) {
$outputBox.Text += Remove-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
$outputBox.Text += ("Connection delete")
$outputBox.Text += Remove-VpnConnection -Name "ConWork" -Force -PassThru -AllUserConnection | Out-String
} else {
$outputBox.text = "No such connection"
}
}
###########end functions################
############Start text fields###########
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(206,23)
$outputBox.Size = New-Object System.Drawing.Size(318,578)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$outputBox.font = "lucida console"
$Form.Controls.Add($outputBox)
###############end text fields################
##############Start buttons################
$CreateTun = New-Object System.Windows.Forms.Button
$CreateTun.Location = New-Object System.Drawing.Size(42,23)
$CreateTun.Size = New-Object System.Drawing.Size(89,43)
$CreateTun.Text = "Create"
$CreateTun.Add_Click({CreateVPN})
$Form.Controls.Add($CreateTun)
$Removetun = New-Object System.Windows.Forms.Button
$Removetun.Location = New-Object System.Drawing.Size(42,90)
$Removetun.Size = New-Object System.Drawing.Size(89,43)
$Removetun.Text = "Delete"
$Removetun.Add_Click({RemoveVPN})
$Form.Controls.Add($Removetun)
############################################## end buttons
#$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
Your problem is that you are checking for VPN connection only once, when the script is started:
$vpnConnection = Get-VpnConnection -AllUserConnection
After that you are reusing this variable to in your RemoveVPN function. It will never find any new connections. To make it work, just move the line from above inside your RemoveVPN function