
是否可以從 powershell 設定檔中偵測 powershell 是否已被互動呼叫?我看到有些人使用$host.name
但它似乎總是返回ConsoleHost
。
答案1
這是一個非常簡單的方法,只要呼叫進程傳遞 -NonInteractive 參數,就可以放入 $PROFILE 中。它可能不適用於所有情況,但正如達拉斯上面提到的,還有其他更複雜的方法這個 Stackoverflow 問題。
if ([Environment]::GetCommandLineArgs().Contains('-NonInteractive')) {
$Global:InteractiveMode=$false
} else {
$Global:InteractiveMode=$true
}
然後,您可以在腳本中使用該變數來執行類似的操作刪除顏色代碼來自批次作業輸出。
if (-not $InteractiveMode) {
# For PWSH 7.2+
$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::PlainText
}