1

Добрый день!

Есть скрипт на powershell, который создает и удаляет vpn соединение у пользователя.

Скрипт представляет собой простую форму с двумя кнопками "Создать" и "Удалить", а также окно вывода служебной информации.

Суть вопроса: если запустить скрипт и нажать создать, то соединение создается. Но если не закрывая формы нажать удалить, то соединение не удаляется. Если форму переоткрыть, то все работает.

Вопрос: в чем может быть проблема?

[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"

##########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 = "Соединение уже есть"
} else {
    Add-VpnConnection -Name "ConWork" -ServerAddress "xxx.xxx.xxx.xxx" -TunnelType IKEv2 -EncryptionLevel Required -AuthenticationMethod Eap -SplitTunneling -RememberCredential -AllUserConnection | Out-String
    $outputBox.Text += ("Соединение создано")
    $outputBox.Text += "`r`n"
    $outputBox.Text += "Добавлены маршруты"
    foreach ($ip in $IpAddress) {
        $outputBox.Text += Add-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
}
#[System.Windows.Forms.MessageBox]::Show("Подключение создано")
}

function RemoveVPN {
if ($vpnConnection.Name -eq "ConWork") {
    $outputBox.Text += ("Удалены маршруты")
    foreach ($ip in $IpAddress) {
        $outputBox.Text += Remove-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
    $outputBox.Text += ("Удалено соединение")
    $outputBox.Text += Remove-VpnConnection -Name "ConWork" -Force -PassThru -AllUserConnection | Out-String
} else {
    $outputBox.text = "Такого соединения нет"
}
}

###########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 = "Создать" 
$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 = "Удалить" 
$Removetun.Add_Click({RemoveVPN}) 
$Form.Controls.Add($Removetun) 

############################################## end buttons

#$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

1 ответ 1

1

Без сообщений об ошибках крайней сложно понять причину. Но я все же попробую предположить, что это связанно с тем, что функции RemoveVPN неизвестно о переменной $IpAddress, а также $vpnConnection т.к. они находятся в разном "пространстве" скрипта. Я заменил scope на script для этих переменных. Вот код:

[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"

##########Constants and Variables########## 

$script:IpAddress = @("172.17.0.0/16", "192.168.197.0/24", "192.168.196.0/24")
$script:vpnConnection = Get-VpnConnection -AllUserConnection

#########Start functions############ 

function CreateVPN {
if ($script:vpnConnection.Name -eq "ConWork") {
    $outputBox.Text = "Соединение уже есть"
} else {
    Add-VpnConnection -Name "ConWork" -ServerAddress "xxx.xxx.xxx.xxx" -TunnelType IKEv2 -EncryptionLevel Required -AuthenticationMethod Eap -SplitTunneling -RememberCredential -AllUserConnection | Out-String
    $outputBox.Text += ("Соединение создано")
    $outputBox.Text += "`r`n"
    $outputBox.Text += "Добавлены маршруты"
    foreach ($ip in $script:IpAddress) {
        $outputBox.Text += Add-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
}
#[System.Windows.Forms.MessageBox]::Show("Подключение создано")
}

function RemoveVPN {
if ($script:vpnConnection.Name -eq "ConWork") {
    $outputBox.Text += ("Удалены маршруты")
    foreach ($ip in $script:IpAddress) {
        $outputBox.Text += Remove-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
    $outputBox.Text += ("Удалено соединение")
    $outputBox.Text += Remove-VpnConnection -Name "ConWork" -Force -PassThru -AllUserConnection | Out-String
} else {
    $outputBox.text = "Такого соединения нет"
}
}

###########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 = "Создать" 
$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 = "Удалить" 
$Removetun.Add_Click({RemoveVPN}) 
$Form.Controls.Add($Removetun) 

############################################## end buttons

#$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.