當我在 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
uj5u.com熱心網友回復:
阿道頓,
請注意,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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327018.html
