Home > Enterprise >  Powershell FolderBrowserDialog behaving differently from shell to ise
Powershell FolderBrowserDialog behaving differently from shell to ise

Time:10-21

When I run the below code in Powershell ISE everything runs fine, but when I run it from Powershell Shell I get a lot of errors about icons.

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |Out-Null

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog 
$foldername.Description = "Select a folder"
$foldername.rootfolder = "MyComputer"
$foldername.SelectedPath = $initialDirectory

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

$folder

Example of Errors:

2021-10-19 15:44:43,174 ERROR - 4600 Unable to get icon for location (The operation completed successfully.): C:\Users\adalton\Pictures\Camera Roll
2021-10-19 15:44:43,176 ERROR - 4600 Unable to get icon for location (The operation completed successfully.): C:\Users\adalton\Pictures\Saved Pictures
C:\Users\adalton\Pictures\Saved Pictures

CodePudding user response:

adalton,

Note that the ISE has things automatically loaded that the CMD version does not and must be loaded by the programmer. The modified code below (read the comments in the code) works on both the ISE and CMD versions of PowerShell 5.1.19041.1237

Add-Type -AssemblyName System.windows.forms

$Folder = @()  #Set up blank array so  = works!

$TermMsg = {
  [Windows.Forms.MessageBox]::Show($Message,
                                   "$Title",
  [Windows.Forms.MessageBoxButtons]::OK ,
  [Windows.Forms.MessageBoxIcon]::Information) | Out-Null}

If ($host.Name -eq 'ConsoleHost' -or
    $host.Name -eq 'Visual Studio Code Host') {

  try{  <# ------------------------------------------------ 
          | Check that the proper assemblies are loaded    |
          | Required for PS Console and Visual Code, while |
          | only Systems.Windows.Forms needed for PSISE!   |
           ------------------------------------------------ 
        #>
    $ATArgs = @{AssemblyName = "PresentationCore",
                               "PresentationFramework",
                               "WindowsBase"
                ErrorAction = 'Stop'}
    Add-Type @ATArgs
  }
  catch {
    $Title   = "Program Terminated:"
    $Message =
        "Failed to load Windows Presentation Framework"  
        " and/or other assemblies required for this program!"
     & $TermMsg
    Exit
  }

} #End If ($host.Name...

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog 
$foldername.Description = "Select a folder"

#Root Folder is restricted see here: 
#https://docs.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=net-5.0
$foldername.rootfolder = [System.Environment SpecialFolder]'MyComputer'

#$foldername.SelectedPath = $initialDirectory

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

$folder
  • Related