Powershell: Input variable prompting a user to select an Organisational Unit from a list

Carl Billington
Carl Billington used Ask the Experts™
on
I am writing a powershell script and one of the input variables that I would like to include is for the user to select an OU from a list.
 
Something like;

$OU = Read-Host (but selecting an OU from a list).
 
I hope this makes sense.
 
Thanks for your help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Assuming PS 3.0 or later, you can use Out-GridView as a make-shift dialog.
$OUSelection = @(
	'OU 1'
	'OU 2'
)
$OU = $OUSelection | Out-GridView -Title 'Please select an OU and click OK' -OutputMode Single
"You've selected the following OU: '$($OU)'" | Write-Host

Open in new window

Author

Commented:
This is great, but is there any way of the script automatically listing all our OU's without listing them all in the section?
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Sure; start with this:
$OUs = Get-ADOrganizationalUnit -Filter * -Properties Description | Select-Object -Property Name, Description, DistinguishedName
$OU = $OUs | Out-GridView -Title 'Please select an OU and click OK' -OutputMode Single
If (-not $OU) {Exit 1}
"You've selected the following OU: '$($OU.DistinguishedName)'" | Write-Host

Open in new window

In the first line, you can of course filter further, for example with the -SearchBase or -Filter argument of Get-ADOrganizationalUnit, or by adding a Where-Clause.

Author

Commented:
Excellent.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial