Powershell FolderBrowserDialog从shell到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:UsersadaltonPicturesCamera Roll
2021-10-19 15:44:43,176 ERROR - 4600 Unable to get icon for location (The operation completed successfully.): C:UsersadaltonPicturesSaved Pictures
C:UsersadaltonPicturesSaved Pictures

adalton,

注意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://learn.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

相关内容

  • 没有找到相关文章