简体   繁体   中英

Get-ADUser triggered by Button

I have a button on a WinForm. After clicking on the button, a function will be called which should execute 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()

Only the two "Write-Host" cmdlets will be executed by clicking on the button.

If I only execute the single line Get-ADUser in the ISE console, it works and I get the user object. Why does Get-ADUser not work when triggered via button?

Thanks

First off, I don't have a full solution as I'm not an expert in WinForms, to feel free to correct/complete this answer.

As far as I know, the command is actually executed. You can check it by stepping though the code or Write-Host -ing bits of the object you collected with Get-ADUser and it will display the correct info:

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

Note that if you replace Write-Host by Write-Output it does not work anymore.

The thing is, when you make a WinForms application, the standard output isn't the console anymore. I don't know where it is redirected to, but it's not visible by default. You need to either specify that you want to see your data in the console with write-host , export it to a file ( Set-Content , Export-Csv , you name it) or display it in a WinForm element:

I added a new TextBox to your form (called $TextBox1 in my example), and changed GeneratePreview like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM