我見過很多尋找New-Object -ComObject Shell.Application
的解決方案,這些解決方案對其他文件執行操作。 (在我的情況下,安裝字體)。ErrorActionPreference =「Stop」會產生令人誤解的錯誤信息
雖然工作在交互模式罰款:
PS C:\> New-Object -ComObject 'Shell.Application'
Application Parent
----------- ------
System.__ComObject System.__ComObject
它沒有這樣做,我的PowerShell腳本里面:
function Install-Font {
Param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.IO.FileSystemInfo[]]
$Files
)
$shell = New-Object -ComObject Shell.Application
echo "Shell: " $shell
echo "Files: " $Files
$Files | ForEach-Object {
$Fonts = $shell.NameSpace($_.Directory.Name)
$font = $Fonts.ParseName($_.Name)
$font.InvokeVerb("Install")
}
}
$ErrorActionPreference = "Stop"
Get-ChildItem $env:TEMP\FiraCode\ttf -Filter *.ttf -File | Install-Font
輸出:
PS C:\Users\villasv\Code\WindowsProSetup> .\testB.ps1
Shell:
ForEach-Object : You cannot call a method on a null-valued expression.
At C:\Users\villasv\Code\WindowsProSetup\testB.ps1:10 char:13
+ $Files | ForEach-Object {
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [ForEach-Object], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull,Microsoft.PowerShell.Commands.ForEachObjectCommand
觀察到$ErrorActionPreference = "Stop"
行事非常可疑。如果我將其刪除,錯誤是完全不同的:
PS C:\Users\villasv\Code\WindowsProSetup> .\testB.ps1
Shell:
Application Parent
----------- ------
System.__ComObject System.__ComObject
Files:
You cannot call a method on a null-valued expression.
At C:\Users\villasv\Code\WindowsProSetup\testB.ps1:12 char:7
+ $font = $Fonts.ParseName($_.Name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\villasv\Code\WindowsProSetup\testB.ps1:13 char:7
+ $font.InvokeVerb("Install")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
調試腳本後,我可以證實,外殼被正確實例化和$Files
參數也是不爲空。
真正的錯誤是我在刪除ErrorActionPreference
時顯示的錯誤。對我來說,這隻能意味着這個設置與stdout打印,代碼分析或類似的東西搞混了。
我無法重現這一點。對我來說工作得很好。 –
我無法重現,在Windows 7/PowerShell 5.0.10586.117 –
我很難想出一個MWE,我會盡快更新。不過,有什麼想法可能會導致這種情況? – VillasV