Hello there, I'm trying to adapt this script:
https://blog.ctglobalservices.com/powershell/kaj/powershell-wpf-treeview-example/
to something that browses the ADUC and pick an OU DN. Everywhere on the Internet has been done with Winforms but I don't want to use that. I've reached a point where I see content in the TreeView but it is shown all at once on one line rather than in hierarchical form and if I expand an item it collapses by showing the same content again as duplicated. The expected result is that it should display the OUs in hierarchical tree order. Any hint or any knowledge I should look up to? C# is not an option on this project, only PS and WPF. Many thanks!
here below the code and:
1. the xaml file is identical to the one used in the link posted.
2. the Select button does not have code yet, I'll do that later.
# Load the Assemblies for the GUI and modules
Add-Type -AssemblyName PresentationFramework
Import-Module ActiveDirectory
# code to handle the import of xaml data
[xml]$xamlWindow = Get-Content "modules\get-ADOU\app.xaml"
$xamlReader = (New-Object System.Xml.XmlNodeReader $xamlWindow)
try{
$MainForm=[Windows.Markup.XamlReader]::Load( $xamlReader )
}catch{
Write-Host "Unable to load Windows.Markup.XamlReader. Some problem is there. Please check the XAML code entered."
exit
}
$xamlWindow.SelectNodes("//*[@Name]") | ForEach-Object{Set-Variable -Name ($_.Name) -Value $MainForm.FindName($_.Name)}
$domainDN = 'OU=Servers,OU=vvv,DC=bbbbb,DC=nnn,DC=ORG'
# Functions
Function Add-OUItem ($Name, $Parent, $Tag) {
#Add new TreeViewItem
$ChildItem = New-Object System.Windows.Controls.TreeViewItem
$ChildItem.Header = $Name
$ChildItem.Name = ""
$ChildItem.Tag = "$Tag\$Name"
[Void]$ChildItem.Items.Add("*")
[Void]$Parent.Items.Add($ChildItem)
}
Function Get-DomainOU ($domainPath, $TreeItem){
$query = Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $domainDN -SearchScope 2
foreach($item in $query){
Add-OUItem -Name $Item.Name -Parent $TreeItem -Tag $domainPath
}
}
# Operations
foreach($item in (Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $domainDN -SearchScope 2)){
Add-OUItem -Name $item.Name -Parent $Tree -Tag "Root"
}
$MainForm.Add_SourceInitialized({
[System.Windows.RoutedEventHandler]$Event = {
if($_.OriginalSource -is [System.Windows.Controls.TreeViewItem]){
$TreeItem = $_.OriginalSource
$TreeItem.items.clear()
Get-DomainOU -domainPath $TreeItem.Tag -TreeItem $TreeItem
Write-Host $TreeView
}
}
$Tree.AddHandler([System.Windows.Controls.TreeViewItem]::ExpandedEvent,$Event)
})
$MainForm.ShowDialog() | Out-Null
