我一直在嘗試創建一個使用輸入來執行其他任務的 Powershell 表單。但是資料需要驗證(不能為空白等......)但是當我運行它并且必須更正一些輸入時,我從回傳的空白和我的最終值中得到多個值。變數也不會離開函式。我嘗試了許多方法,例如 Clear-Variable 和 Out-Null,我知道這與 Powershell 處理回傳資料的方式有關,但我被卡住了。我這里有一個簡化版本:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName Microsoft.VisualBasic
$BuildName = ""
function Enter-BuildInfo {
# Create a new form
$CoreForm = New-Object system.Windows.Forms.Form
$CoreForm.ClientSize = ‘220,100’
$CoreForm.text = “Enter Name”
$CoreForm.BackColor = “#03335a”
$Coreform.StartPosition = 'CenterScreen'
$Coreform.Topmost = $true
$OKButton = New-Object System.Windows.Forms.Button -Property @{
Location = New-Object System.Drawing.Size(160,60)
Size = New-Object System.Drawing.Size(50,25)
BackColor = "#ffffff"
Text = 'OK'
DialogResult = [System.Windows.Forms.DialogResult]::OK
}
$CoreForm.AcceptButton = $OKButton
$CoreForm.Controls.Add($OKButton)
### Inserting the text box that will accept input
$textbox1 = New-Object System.Windows.Forms.TextBox
$textbox1.Location = New-Object System.Drawing.Point(10,25) ### Location of the text box
$textbox1.Size = New-Object System.Drawing.Size(175,25) ### Size of the text box
$textbox1.Multiline = $false ### Allows multiple lines of data
$textbox1.AcceptsReturn = $false ### By hitting enter it creates a new line
#$textbox1.ScrollBars = "Vertical" ### Allows for a vertical scroll bar if the list of text is too big for the window
$Coreform.Controls.Add($textbox1)
$BuildName = $textbox1.text
$Coreresult = $CoreForm.ShowDialog()
if ($Coreresult -eq [Windows.Forms.DialogResult]::OK)
{
$BuildName = $textbox1.text
}
if ($BuildName -ne "")
{
Write-Host "Click OK Name: $BuildName "
}
else
{
[Microsoft.VisualBasic.Interaction]::MsgBox("BuildName can not be blank",'OKOnly,SystemModal,Information', 'Retry Name')
Enter-BuildInfo
}
Write-Host "Inside Function Name: $BuildName "
}
Enter-BuildInfo
Write-Host "Out of Function Name: $BuildName "
我的結果:
Ok
Click OK Name: Test Name
Inside Function Name: Test Name
Inside Function Name:
Out of Function Name:
uj5u.com熱心網友回復:
函式中定義的變數永遠不會對函式的呼叫者可見。
- 讓你的函式的輸出資料(也不能使用
Write-Host為)你想要的來電者看到,該來電者必須捕獲($output = Enter-BuildInfo)
- 讓你的函式的輸出資料(也不能使用
通過在表單關閉(從呼叫回傳)之前呼叫的事件處理程式在 WinForm 表單中執行輸入驗證。
.ShowDialog()這樣就不需要遞回呼叫您的函式,這會使問題復雜化。
具體來說:
- 將您
$OKButton的.Enabled屬性初始化為$false - 將事件處理程式(腳本塊)傳遞給
$textbox1.add_TextChanged(),您$OKButton僅在以下情況下啟用$textbox1.Text.Trim() -ne ''
- 將您
注意:要處理基于多個其他控制元件的 OK 按鈕的啟用邏輯:
定義一個函式,該函式根據所有相關控制元件的狀態實作驗證邏輯。
從傳遞給
.add_{eventName}()所有相關控制元件的方法的腳本塊中呼叫該函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380570.html
