Powershell FolderBrowserDialog 的行为与 shell 不同

Powershell FolderBrowserDialog behaving differently from shell to ise

当我在 Powershell ISE 中 运行 下面的代码时,一切 运行 都很好,但是当我从 Powershell 运行 中 Shell 时,我得到了很多错误图标。

[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

错误示例:

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

阿道尔顿,

请注意,ISE 会自动加载 CMD 版本不会加载的内容,并且必须由程序员加载。下面修改后的代码(阅读代码中的注释)适用于 PowerShell 5.1.19041.1237

的 ISE 和 CMD 版本
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