2017-01-05 32 views
1

我見過很多尋找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打印,代碼分析或類似的東西搞混了。

+1

我無法重現這一點。對我來說工作得很好。 –

+0

我無法重現,在Windows 7/PowerShell 5.0.10586.117 –

+0

我很難想出一個MWE,我會盡快更新。不過,有什麼想法可能會導致這種情況? – VillasV

回答

0

我認爲這很清楚。 你得到的第一個錯誤並不重要。它是「shell」的回聲之一:$ shell 您至少需要像「shell:$ shell」或「shell:」+ $ shell 相同$文件

第二個是關鍵一。 您嘗試將null發送到foreach對象。

所以,如果你不調整默認的錯誤行爲。 他會吞下第一個錯誤,並在第二個錯誤上失敗。

順便嘗試使用寫主機,而不是回聲。 如果你認爲像powershell,你會像powershell。

+0

第一個不是錯誤(儘管做得不好),它只是單獨地「回聲」。第二個也不是錯誤,因爲就像我所說的,'$ Files'不是null。 – VillasV