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
Related
With the below code, my goal is to ping a hostname and have it return if successful or unsuccessful, and project that on the GUI screen itself. At the moment I am getting errors on the "-TargetName".
Add-Type -assembly System.Windows.Forms
# Create window form
$main_form = New-Object System.Windows.Forms.Form
$main_form.Text = 'Device Info'
$main_form.Width = 600
$main_form.Height = 400
$main_form.AutoSize = $true
# Start of code
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Hostname"
$Label.Location = New-Object System.Drawing.Point(10, 30)
$Label.AutoSize = $true
$main_form.Controls.Add($Label)
# Adding textbox
$TextBox = New-Object System.Windows.Forms.TextBox
$TextBox.Location = New-Object System.Drawing.Point(90, 30)
$TextBox.Width = 300
$main_form.Controls.Add($TextBox)
# Adding check button
$CheckButton = New-Object System.Windows.Forms.Button
$CheckButton.Location = New-Object System.Drawing.Size(400, 30)
$CheckButton.Size = New-Object System.Drawing.Size(120, 23)
$CheckButton.Text = "Check"
$main_form.Controls.Add($CheckButton)
# Perform event when check button is clicked
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
# Show Window
$main_form.ShowDialog()
You need to grab the value from $TextBox.Text when the button is clicked, and then use the correct parameter name (-ComputerName rather than -TargetName)!
Change this:
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
To:
$CheckButton.Add_Click(
{
$ComputerName = $TextBox.Text
Test-Connection -ComputerName $ComputerName -IPv4
}
)
I have the below code that used to work fine with Powershell x64. Long story short, there is something corrupted with the config file for x64 which I am waiting to get fixed (I do not have admin access to fix; separate issue).
The top five lines of code are included to force Powershell 32-bit to run, and it indeed works. My issue is that, for some reason, after successfully running with the 32-bit .exe, the code runs a second time with the 64-bit .exe, which of course throws all sorts of errors related to the config file issues.
Errors aside, is there any obvious piece of code that causes everything from line 7 and on to run a second time?? I will do my best to provide any more information that you might need in assisting me with this issue.
NOTE: The entire code set from line 7 and on works perfectly fine, so nothing needs to be changed besides fixing this loop.
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
if ($env:Processor_Architecture -ne "x86")
{ &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path }
$env:Processor_Architecture | Out-Null
[IntPtr]::Size | Out-Null
if ($startupvariables) { try {Remove-Variable -Name startupvariables -Scope Global -ErrorAction SilentlyContinue } catch { } }
New-Variable -force -name startupVariables -value ( Get-Variable | ForEach-Object { $_.Name } )
Add-Type -AssemblyName PresentationCore,PresentationFramework
$ButtonType = [System.Windows.MessageBoxButton]::OKCancel
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
$MessageTitle = "Strike 1"
$MessageBody = "This script sends the user Strike 1 of the 3 strike process.`n`nTo use it, enter the below information:`n`n`n`tTicket Number`n`n`tUser's Email Address`n`n`tInformation that you want to convey to user`n`n`nIf this is the script you want to use, click OK.`nIf not, click Cancel."
$Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
if ($Result -eq "Cancel")
{
Exit-PSSession
}
else
{
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Separator = ".", "#"
$Ticket = [Microsoft.VisualBasic.Interaction]::InputBox("Enter ticket number" , "Ticket Number")
$UserID = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the user's email address" , "User Email Address")
function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Size(10,10)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.AutoSize = $true
$label.Text = $Message
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Size(10,40)
$textBox.Size = New-Object System.Drawing.Size(575,200)
$textBox.AcceptsReturn = $true
$textBox.AcceptsTab = $false
$textBox.Multiline = $true
$textBox.ScrollBars = 'Both'
$textBox.Text = $DefaultText
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Size(415,250)
$okButton.Size = New-Object System.Drawing.Size(75,25)
$okButton.Text = "OK"
$okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() })
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Size(510,250)
$cancelButton.Size = New-Object System.Drawing.Size(75,25)
$cancelButton.Text = "Cancel"
$cancelButton.Add_Click({ $form.Tag = $null; $form.Close() })
$form = New-Object System.Windows.Forms.Form
$form.Text = $WindowTitle
$form.Size = New-Object System.Drawing.Size(610,320)
$form.FormBorderStyle = 'FixedSingle'
$form.StartPosition = "CenterScreen"
$form.AutoSizeMode = 'GrowAndShrink'
$form.Topmost = $True
$form.AcceptButton = $okButton
$form.CancelButton = $cancelButton
$form.ShowInTaskbar = $true
$form.Controls.Add($label)
$form.Controls.Add($textBox)
$form.Controls.Add($okButton)
$form.Controls.Add($cancelButton)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog() > $null
return $form.Tag
}
$Issue = Read-MultiLineInputBoxDialog -Message "What is the information you want to convey to the user?" -WindowTitle "Information Requested"
$User = $UserID.split($Separator)
$Firstname = $User[0].substring(0,1).toupper()+$User[0].substring(1).tolower()
$Lastname = $User[1].substring(0,1).toupper()+$User[1].substring(1).tolower()
$User = $Firstname, $Lastname
$Username = [System.Environment]::UserName
$subject = "Ticket $Ticket on Hold for User Response - Status Reminder #1"
$body = "
To $User,
Your IT Service Desk ticket is currently in Hold for User Confirmation/Input status while we wait for feedback/action from you. Without your feedback/action we cannot continue our efforts to resolve this ticket.
$Issue
As per policy, if a response is not received within 2 business days of your ticket being changed to Hold for User Confirmation/Input status, we will consider your issue resolved.
Thank You,
IT Service Desk
"
$ButtonType = [System.Windows.MessageBoxButton]::YesNo
$MessageIcon = [System.Windows.MessageBoxImage]::Warning
$MessageTitle = "Strike 1"
$MessageBody = "The information you have entered is show below:`n`n`nTicket Number: $Ticket`n`nUser's Email Address: $UserID`n`nInformation Requested: $Issue`n`n`nIf you would like to send the email, click Yes.`nOtherwise, click No."
$Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
if ($Result -eq "No")
{
Exit-PSSession
}
else
{
Send-MailMessage -To "<$UserID>" -bcc "<$Username#email.com>" -from "<itservicedesk#email.com>" -Subject $subject -SmtpServer "mailrelay.email.com" -body $body
}
}
Function Clean-Memory {
Get-Variable |
Where-Object { $startupVariables -notcontains $_.Name } |
ForEach-Object {
try { Remove-Variable -Name "$($_.Name)" -Force -Scope "global" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue}
catch { }
}
}
the issue is here
if ($env:Processor_Architecture -ne "x86")
{ &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path }
When you run this in a powershell x64 all you are doing is starting the x86 powershell but not killing the x64 so the x64 keeps running the script.
Add a exit like
if ($env:Processor_Architecture -ne "x86"){
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path
exit
}
So I have about wrapped up my holiday break personal project.
I have a form that refreshes on a set interval(which with this last problem solved will start creating a config file)
Before I added the on_tick function and on load function that allowed for the functionality I wanted, the program ran fine if not the results I wanted. When I mean ran fine I mean if I clicked close("X" button in top right) or wanted to move the window I could
After I added the fixes for refresh The Form window is now unresponsive or will take forever to register a "close" command
########################################################################
#Purpose to have a UI running at a 30 second intervel to update on
#network and machine performance metrics
########################################################################
function OnApplicationLoad {
return $true
}
function OnApplicationExit {
$script:ExitCode = 0
}
function Get-ComputerStats {
process {
$avg = Get-WmiObject win32_processor |
Measure-Object -property LoadPercentage -Average |
Foreach {$_.Average}
$mem = Get-WmiObject win32_operatingsystem |
Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
$free = Get-WmiObject Win32_Volume -Filter "DriveLetter = 'C:'" |
Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity)*100)}
[pscustomobject] [ordered] #{
ComputerName = $env:computername
AverageCpu = $avg
MemoryUsage = $mem
PercentFree = $free
}
}
}
function GenerateForm {
[void][reflection.assembly]::Load("System.Windows.Forms, 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("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = New-Object System.Windows.Forms.Form
$button = New-Object System.Windows.Forms.Button
$outputBox = New-Object System.Windows.Forms.RichTextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 30000
$form.ForeColor = "#25c420"
$form.BackColor = "#000000"
#tick function - code that actually gets the metrics all other code is for the silly gui
Function Timer_Tick(){
$date = Get-Date -Format "HH:mm:ss"
$form.Text = "Network and Health Monitor ($date)"
$outputBox.ForeColor = "#25c420"
$outputBox.BackColor = "#000000"
$outputBox.Text += "`n"
$pySpeedDir = "C:\Users\CentralTerminal\AppData\Local\Programs\Python\Python36\Scripts\pyspeedtest.exe"
$speed = & $pySpeedDir
$table = Get-ComputerStats | Select-Object ComputerName,AverageCpu,MemoryUsage,PercentFree | Out-String
#$outputBox.Text += get-date
$outputBox.Text += "$date`n"
$outputBox.Text += "CPU and Memory Utilization`n"
$outputBox.Text += $table
$outputBox.Text += "`r`n"
$outputBox.Text += "Network Test in Progress...`n"
$outputBox.Text += $speed[0]+ "`n" + $speed[1] + "`n" + $speed[2] + "`n" + $speed[3]
$outputBox.Text += "`r`n"
$outputBox.Select()
$outputBox.SelectionStart = $outputBox.Text.Length
$outputBox.ScrollToCaret()
$outputBox.Refresh()
}
Function Form_Load{
#$form.Text = "Timer started"
Timer_Tick
$timer.Start()
}
$form_StateCorrection_Load={
$form.WindowState = $InitialFormWindowState
}
$form.Controls.Add($outputBox)
$form.Text = "Network and Machine Load"
$form.Name = "GUM"
$form.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$form.ClientSize = New-Object System.Drawing.Size(800,400)
$form.BackgroundImageLayout = "None"
$form.add_Load({Form_Load})
$timer.Add_Tick({Timer_Tick})
$outputBox.Name = "outputBox"
$outputBox.Text = ""
$outputBox.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$outputBox.Location = New-Object System.Drawing.Point(5,35)
$outputBox.Size = New-Object System.Drawing.Size(785,320)
$outputBox.font = "lucida console"
$outputBox.TabIndex = 0
$InitialFormWindowState = $form.WindowState
$form.add_Load($form_StateCorrection_Load)
return $form.ShowDialog()
}
if(OnApplicationLoad -eq $true){
GenerateForm | Out-Null
OnApplicationExit
}
My problem is that I have no exceptions being thrown. I am going to add a try catch to this system as well but there are no error messages or anything that is technically breaking for me to start my investigation. If you also just know where to start debugging that would be helpful too as I am trying to get better at Production Support in general
Thanks for reading
I have observed a difference in behavior between PowerShell 2.0 code and 3.0 code but can't seem to fix it. I am hoping I can get some help. Please see code below.
If you run this in V2 (please change ServerA and ServerB to a server on your network) you will see after selecting and clicking the button, write-host shows them as seperate names. In version 3 the listbox populates it as 1.
$Servers = #()
[array]$ServerstoPing = ("ServerA","ServerB")
# Generate the form
Add-Type -AssemblyName System.Windows.Forms
$Form1 = New-Object system.Windows.Forms.Form
$Form1.Text = "Ping Some Servers"
$Font = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::regular)
$Fontboxes = New-Object System.Drawing.Font("Lucida Sans",8,[System.Drawing.FontStyle]::regular)
$Fontdate = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$FontProgress = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$Form1.Font = $Font
$Serverlistbox = New-Object System.Windows.Forms.Listbox
$Serverlistbox.Location = New-Object System.Drawing.Size(11,137)
$Serverlistbox.Size = New-Object System.Drawing.Size(200,170)
$Serverlistbox.SelectionMode = "MultiExtended"
$Serverlistbox.font = $Fontboxes
foreach($item in $ServerstoPing){
[void] $Serverlistbox.Items.Add("$item")
}
$Form1.Controls.Add($Serverlistbox)
$SubmitButton = New-Object System.Windows.Forms.button
$SubmitButton.text = "Ping Servers"
$SubmitButton.Location = New-Object System.Drawing.Size(171,305)
$SubmitButton.AutoSize = $True
$Form1.Controls.Add($SubmitButton)
$Form1.StartPosition = "CenterScreen"
$OutputPing = New-Object System.Windows.Forms.TextBox
$OutputPing.MultiLine = $True
$OutputPing.ScrollBars = "Vertical"
$OutputPing.text = "Server ping status will be displayed here once done'."
$OutputPing.font = $Fontboxes
$OutputPing.Location = New-Object System.Drawing.Size(226,40)
$OutputPing.Size = New-Object System.Drawing.Size(200,255)
$Form1.Controls.Add($OutputPing)
$SubmitButton.add_click({
#foreach ($objItem in $ServerstoPing)
foreach ($objItem in $Serverlistbox.SelectedItems)
{
$Servers += $objItem
}
write-host $ServerstoPing
Foreach($server in $servers)
{
ping -n 1 -w 1000 $server | out-null
if($? -eq $true){
write-host ("$server ping success")
}
else
{
write-host ("$server did not respond to ping, not extracting events")
}
}
})
$Form1.ShowDialog()
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.