![](/img/trans.png)
[英]Don't throw PowerShell exception on writes to stderr from external command
[英]Search my code and throw exception from Powershell
我將如何編寫一個腳本來搜索我的代碼文件中的關鍵短語(例如 jasmine 單元測試中的“fit(”),如果找到則拋出異常。我不介意提供頂級文件夾,但它應該搜索通過子文件夾。如果我可以將數組中的關鍵短語傳遞給它,我也可以加分。我也可以安裝一個節點包來方便。
我的包 json 文件中有一個腳本,用於“簽入”文件。 它構建所有,運行所有測試,暫存文件,然后提交它們。 我想在開頭添加它,如果發現禁止短語,則退出(不是構建 -> 測試等)。 (可能會調試像 fit、不推薦使用的方法之類的標志)。
"commit-all": "ng build core-library --prod && ng build --prod && echo Executing tests && ng test --browsers ChromeHeadless --no-watch --codeCoverage=false && git checkout tsconfig.json && git checkout src/environments/environment.ts && git add . && git commit -m "
您可以按如下方式組合Get-ChildItem
、 Select-String
和ForEach-Object
cmdlet:
$dir = '...' # specify the directory whose subtree to search.
Get-ChildItem $dir -Recurse -File -Filter *.ps1 |
Select-String 'fit(', 'fun(' -List |
ForEach-Object { Throw "Phrase found: $($_ | Out-String)" }
如果您將上述內容打包為腳本,則使用Throw
將使您的腳本報告退出代碼1
。
或者,如果您想在報告錯誤之前查找並報告所有匹配項,請省略ForEach-Object
調用,使用$matchesFound = Get-ChildItem ...
收集所有匹配項並與它們一起拋出,或使用Write-Error
並手動調用exit 1
.
要通過CLI調用腳本,請使用:
# PowerShell [Core] executable shown; use powershell.exe for Windows PowerShell
pwsh -NoProfile -File YourScript.ps1
注意:遺憾的是,PowerShell CLI 通過stdout意外報告錯誤,並且錯誤消息在 Windows PowerShell 中很嘈雜並且跨越多行 - 請參閱此答案以獲取解決方法和背景信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.