PowerShell GUI中窗体内调用函数执行Get-AdfsRelyingPartyTrust无响应问题
问题根因
- 命令拼写错误:
Get-AdfsReylingPartyTrus存在拼写错误,正确命令名为Get-AdfsRelyingPartyTrust,拼写错误导致命令无法执行且无报错 - 对话框结果判断逻辑错误:OK按钮的
DialogResult属性设置为数值1,对应枚举值[System.Windows.Forms.DialogResult]::OK,但代码中使用字符串"OK"做判断,两者不相等导致执行分支永远不会触发 - 执行结果未显式输出:函数内命令执行的返回值默认作为函数返回值,在按钮点击事件中调用时不会直接打印到控制台,需要主动指定输出
修复代码
function single_rpt{ $RPTForm = New-Object System.Windows.Forms.Form $RPTForm.ClientSize = '400,200' $RPTForm.Text = "Choose" $RPTForm.BackColor = "#b2b2b2" $RPTForm.AutoSize = $false $RPTForm.StartPosition = 'CenterScreen' $RPTForm.ControlBox = $true $rptButton = New-Object System.Windows.Forms.Button $rptButton.BackColor = "#ffffff" $rptButton.Text = "OK" $rptButton.Width = 90 $rptButton.Height = 30 $rptButton.Location = New-Object System.Drawing.Point(20,125) $rptButton.Font = 'Microsoft Sans Serif,10' $rptButton.ForeColor = "#000000" $rptButton.UseVisualStyleBackColor = $true $rptButton.DialogResult = [System.Windows.Forms.DialogResult]::OK # Test List Box $listBox = New-Object System.Windows.Forms.ListBox $listBox.Location = New-Object System.Drawing.Point(20,50) $listBox.Size = New-Object System.Drawing.Size(350,200) $listBox.Height = 80 $RPTForm.Controls.AddRange(@($listBox,$rptButton)) $listboxArray = @() $ADFS_RPTS = Get-AdfsRelyingPartyTrust Foreach($rpt in $ADFS_RPTS) { $listboxArray += $rpt.Name } $listBox.Items.AddRange($listboxArray) [void]$RPTForm.ShowDialog() if($RPTForm.DialogResult -eq [System.Windows.Forms.DialogResult]::OK) { $selectedRPT = $listBox.SelectedItem.ToString() # 执行正确命令并输出结果到控制台 Get-AdfsRelyingPartyTrust -Name $selectedRPT | Out-Host } } # Init PowerShell Gui Add-Type -AssemblyName System.Windows.Forms # Create Form with size, title and background color, etc. $TESTForm = New-Object System.Windows.Forms.Form $TESTForm.ClientSize = '250,300' $TESTForm.Text = "TEST" $TESTForm.BackColor = "#ffffff" $TESTForm.AutoSize = $false $TESTForm.StartPosition = 'CenterScreen' $TESTForm.ControlBox = $true $RPTSingle = New-Object System.Windows.Forms.Button $RPTSingle.BackColor = "#ffffff" $RPTSingle.Text = "RPTSingle" $RPTSingle.Width = 90 $RPTSingle.Height = 30 $RPTSingle.Location = New-Object System.Drawing.Point(75,125) $RPTSingle.Font = 'Microsoft Sans Serif,10' $RPTSingle.ForeColor = "#000000" $RPTSingle.UseVisualStyleBackColor = $true $RPTSingle.Add_Click({single_rpt}) # Add a Cancel Button $CancelButton = New-Object System.Windows.Forms.Button $CancelButton.BackColor = "#ffffff" $CancelButton.Text = "Cancel" $CancelButton.Width = 90 $CancelButton.Height = 30 $CancelButton.Location = New-Object System.Drawing.Point(75,250) $CancelButton.Font = 'Microsoft Sans Serif,10' $CancelButton.ForeColor = "#000000" $CancelButton.UseVisualStyleBackColor = $true $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $TESTForm.Controls.AddRange(@($RPTSingle,$CancelButton)) # Display the form [void]$TESTForm.ShowDialog()
内容的提问来源于stack exchange,提问作者PSDude
相关产品推荐
相关产品推荐

