【问题标题】:Get-ADUser triggered by Button按钮触发的 Get-ADUser
【发布时间】:2019-12-20 22:12:50
【问题描述】:

我在 WinForm 上有一个按钮。单击按钮后,将调用一个函数,该函数应执行 Get-ADUser cmdlet。

Add-Type -AssemblyName System.Windows.Forms 
Add-Type -AssemblyName System.Data 
Import-Module ActiveDirectory

$ctl_frm_aduserlist = New-Object System.Windows.Forms.Form -Property @{
    Size = New-Object System.Drawing.Size(500,500)
    StartPosition = "CenterScreen" } 
$ctl_btn_generatepreview = New-Object System.Windows.Forms.Button -Property @{
        Size = New-Object System.Drawing.Size(200,30)
        Location = New-Object System.Drawing.Point(10,30)
        Text = "Generate Preview" } 
$ctl_frm_aduserlist.Controls.Add($ctl_btn_generatepreview)

$ctl_btn_generatepreview.Add_Click({ GeneratePreview })

function GeneratePreview(){
    Write-Host "GO"
    Get-ADUser -Identity "user123" -Properties Name,SamAccountName | select Name,SamAccountName
    Write-Host "END" }

$ctl_frm_aduserlist.ShowDialog()

单击按钮只会执行两个“Write-Host”cmdlet。

如果我只在 ISE 控制台中执行单行 Get-ADUser,它会起作用并且我会得到用户对象。 为什么Get-ADUser在按钮触发时不起作用?

谢谢

【问题讨论】:

  • 请添加您的 WinForms 按钮的代码
  • 尝试将 GeneratePreview()-Function 放在 Add-Type 行之后。
  • @LuttiCoelho 代码在那里..
  • @f6a4 我把它放在那里并再次尝试。还是不行
  • 在 ISE 中,默认输出到主机控制台。在表单中,您不会告诉对象“去哪里”。将输出通过管道传输到“Out-Host”以获得您想要的结果。

标签: winforms powershell


【解决方案1】:

首先,由于我不是 WinForms 专家,因此我没有完整的解决方案,请随时更正/完成此答案。

据我所知,该命令实际上是执行的。您可以通过使用Get-ADUser 收集的对象的代码或Write-Host-ing 位来检查它,它将显示正确的信息:

function GeneratePreview() {
    Get-ADUser -Identity "someone" | Write-Host
}

请注意,如果您将Write-Host 替换为Write-Output,它将不再起作用。

问题是,当您制作 WinForms 应用程序时,标准输出不再是控制台。我不知道它被重定向到哪里,但默认情况下它是不可见的。您需要使用write-host 指定要在控制台中查看数据,将其导出到文件(Set-ContentExport-Csv,您可以命名)或在 WinForm 元素中显示:

我在表单中添加了一个新的 TextBox(在我的示例中称为 $TextBox1),并像这样更改了 GeneratePreview:

function GeneratePreview() {
    $user = Get-ADUser "someone"
    $TextBox1.Text = "$($user.name),$($user.samaccountname)"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多