我目前正在研究一個 powershell gui,我想在結束事件中添加一個命令。在啟動 gui 時,我正在加載一個會話,我想在離開時關閉它。
這是我的腳本的一部分:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyle()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = '1300,700'
$Form.Text = "Test close event"
$Form.Add_Closing({
Param($sender,$e)
$result = [System.Windows.Forms.MessageBox]::show(`
"wish to quit?",`
"quit",[System.Windows.Forms.MessageBoxButtons]::YesNoCancel)
If($result -ne [System.Windows.Forms.DialogResult]::Yes)
{
Get-PSSession |Remove-PSSession
$e.Cancel = $true
}
})
$session = New-PSSession -ConfigurationName Microsoft.exchange -URI "server" -Authentication Kerberos
Import-PSSession $session | Out-Null
... Rest of the script ...
$Form.ShowDialog()
其余的作業正常,但這部分似乎有問題。如果有人有想法我很感興趣。
uj5u.com熱心網友回復:
如果我理解正確,您在關閉時的表格會顯示“希望退出?” 問題成功,然后它成功執行Get-PSSession | Remove-PSSession。但是一旦全部完成,您會看到您的 Exchange 連接仍然處于活動狀態。
如果是這種情況,下面的方法應該可以作業——對你的 $session 變數使用“script:”范圍。
代碼片段:
$script:session = New-PSSession -ConfigurationName Microsoft.exchange -URI "server" -Authentication Kerberos
Import-PSSession $script:session | Out-Null
Remove-PSSession $script:session
完整代碼:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyle()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = '1300,700'
$Form.Text = "Test close event"
$Form.Add_Closing({
Param($sender,$e)
$result = [System.Windows.Forms.MessageBox]::show(`
"wish to quit?",`
"quit",[System.Windows.Forms.MessageBoxButtons]::YesNoCancel)
If($result -ne [System.Windows.Forms.DialogResult]::Yes)
{
Remove-PSSession $script:session
$e.Cancel = $true
}
})
$script:session = New-PSSession -ConfigurationName Microsoft.exchange -URI "server" -Authentication Kerberos
Import-PSSession $script:session | Out-Null
... Rest of the script ...
$Form.ShowDialog()
注意由于我們使用“script:”前綴參考會話變數,因此您應將代碼保存在 *.ps1 檔案中并將其作為腳本運行,例如PS> C:\scripts\myscript.ps1
參考: about_Scopes
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428157.html
上一篇:如何在PLSQLRestService中傳遞JSON陣列
下一篇:具有2行寬度大小的Wpf網格
