1
votes

I have seen the post "How to properly use the FolderBrowserDialog in Powershell"

I am having an issue getting just the path selected to return from the function.

At the end of the script I "write-host $a" but instead of getting just the directory I selected (C:\Temp) I get System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 C:\Temp

Function Get-Folder($initialDirectory)

{ [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"

if($foldername.ShowDialog() -eq "OK")
{
    $folder += $foldername.SelectedPath
}
return $folder

}

$a = Get-Folder Write-Host $a

I was told this is obsolete and to use Add-Type. Not getting just the path with the following script.

   Add-Type -AssemblyName System.Windows.Forms
   $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
   [void]$FolderBrowser.ShowDialog()
   $FolderBrowser.SelectedPath
   Write-Host "FolderBrowser= "$FolderBrowser
1
You probably have $folder defined outside the scope of the function, and the function is modifying that. Close PowerShell and re-launch it. Also, change your $folder += to just $folder =. - TheMadTechnician
thanks! its working with the help of you and Jon - Shannon

1 Answers

2
votes

You are getting that result because this line also produces output:

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

PowerShell returns all output from a function so your results are actually an array containing the output from the loading of the assembly and the folder name.

Adding [void] in front of the assembly loading operation like this will omit that extra output and give you the results you are expecting:

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

Or as Anthony Stringer mentions in the comments, you can use Add-Type instead which does not produce any output and would probably be the preferred method:

Add-Type -AssemblyName System.Windows.Forms

Also, TheMadTechnician is correct that you don't need the +=, just the = for the $folder variable.

This answer explains the behavior of returning output from a PowerShell function in more detail.