Script giving weird output

Welcome Forums General PowerShell Q&A Script giving weird output

This topic contains 3 replies, has 2 voices, and was last updated by

 
Participant
8 months ago.

  • Author
    Posts
  • #95703

    Participant
    Points: 0
    Rank: Member

    I have a script to list all AD OUs but for some reason the foreach is giving output of an integer of each OU

    I run it and it outputs for example if there is 10 OUs

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
    
    $objForm = New-Object System.Windows.Forms.Form 
    $objForm.Text = "Select an OU"
    $objForm.Size = New-Object System.Drawing.Size(500,200) 
    $objForm.StartPosition = "CenterScreen"
    
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.AutoSize = $True
    $OKButton.Location = New-Object System.Drawing.Size(200,120)
    $OKButton.Text = "OK"
    $OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})
    $objForm.Controls.Add($OKButton)
    
    $objLabel = New-Object System.Windows.Forms.Label
    $objLabel.Location = New-Object System.Drawing.Size(10,20) 
    $objLabel.Size = New-Object System.Drawing.Size(280,20) 
    $objLabel.Text = "Please select an OU"
    $objForm.Controls.Add($objLabel) 
    
    $objListBox = New-Object System.Windows.Forms.ListBox 
    $objListBox.Location = New-Object System.Drawing.Size(10,40) 
    $objListBox.Size = New-Object System.Drawing.Size(460,20) 
    $objListBox.Height = 80
    
    $OUlist = (Get-ADOrganizationalUnit -Filter *)
    
    ForEach ($OU in $OUlist)
    {$objListBox.Items.Add($OU.DistinguishedName)}
    
    $objForm.Controls.Add($objListBox) 
    
    $objForm.Topmost = $True
    
    $objForm.Add_Shown({$objForm.Activate()})
    [void] $objForm.ShowDialog()
    
    $NewOU = $objListBox.SelectedItem
    $NewOU
    

    Thanks
    Daniel

  • #95706

    Keymaster
    Points: 1,619
    Helping HandTeam Member
    Rank: Community Hero

    SelectedItem is an integer, referring to the index of the item which is selected. If you're after the OU name, you may want to try SelectedText or something instead. Read through the docs on that ListBox control.

  • #95709

    Participant
    Points: 0
    Rank: Member

    It give the OU name as well when i select it in the list box and click OK. Also if i comment out the last two lines it still lists the numbers, just not the OU obviously

    Daniel

  • #95717

    Participant
    Points: 0
    Rank: Member

    it have been fixed!

    [Void] was needed in the foreach

    ForEach ($OU in $OUlist)
    {[Void]$objListBox.Items.Add($OU.DistinguishedName)}
    

The topic ‘Script giving weird output’ is closed to new replies.