我有以下PowerShell代碼
ls "*.zip" | % {
$name = $_.name
if (-not ($name -match '(?<x>\d\d)(?<y>\d{4})\.zip')) { continue }
$p = $matches["y"] + $matches["x"]
}
代碼工作以及在ISE。但是,如果它在命令行shell中運行,則會出現以下錯誤。
Cannot index into a null array. At line:3 char:19 + $p = $matches[ <<<< "y"] + $matches["x"] + CategoryInfo : InvalidOperation: (y:string) [], RuntimeException + FullyQualifiedErrorId : NullArray
編輯
我使用if (-not ...) { continue }
,因爲我不想讓太多的括號縮進。我糾正了-not()
問題。 (它沒有涉及到的錯誤,雖然,我測試了它的名字總是在xxx999999.zip格局中的文件)
PowerShell *具有*語言規範。在ISE和命令行中,語言的運行方式相同(實際上,主機cmdlet的行爲不同)。畢竟這是整個問題。 – Joey 2012-08-03 05:37:39
請注意,您的代碼省略了他們犯的實際錯誤。這是它工作的原因。我會說程序員在這裏是不可預知的,而不是語言。 – Joey 2012-08-03 05:40:53
此外,在第一次找到不匹配的文件時繼續中止管道。 – JPBlanc 2012-08-03 06:03:56