![](/img/trans.png)
[英]Script Works in Powershell CLI but not in ISE or as a PS1
[英]PS1 script works normal in ISE but displays my -AsSecureString text when in Exe?
我現在正在編寫一個腳本,但我無法弄清楚為什么添加到腳本中會使我的 -AsSecureString 在使用 ISEsteroids 編譯到 CMD/window (.*Exe) 時在完成的結果中回顯。
我正在使用“Read-Host”在上面使用並隱藏腳本中寫入的密碼。 在編輯器中運行代碼時效果很好。 但是,當使用 ISEsteroids 編譯以執行我的腳本時,我的腳本運行,然后最后以純文本回顯密碼 3 次......就像這樣(圖像)
我使用它在兩者之間添加“再次運行”框和腳本。
$choices = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes","&No")
while ( $true ) {
腳本在這里......
$Host.UI.RawUI.WindowTitle = $PSScriptRoot
$choice = $Host.UI.PromptForChoice("Run again","",$choices,0)
if ( $choice -ne 0 ) {
break
}
}
伊勢 output:
Output 來自可執行文件:
更新 -已解決來自 @mklement0 的幫助。 這解決了這個問題。
while ([Console]::KeyAvailable) { $null = [Console]::ReadKey($true) }
tl;博士
作為您在編譯的應用程序中看到的意外行為的解決方法 - 響應Read-Host
鍵入的字符也顯示在稍后的不相關提示中 - 在調用$Host.UI.PromptForChoice(...)
之前清除控制台鍵盤緩沖區(取自這個答案):
# Clear any pending keystrokes.
while ([Console]::KeyAvailable) { $null = [Console]::ReadKey($true) }
行為差異歸結為不同的 PowerShell主機實現。
A PowerShell host is a .NET class derived from the abstract System.Management.Automation.Host.PSHost
class, and its purpose is to provide input to and display output from the PowerShell runtime.
不同的 PowerShell 環境具有不同的主機實現,其行為可能會有很大差異,並且允許主機不實現某些功能。 $Host.Name
報告主機的友好名稱,例如常規控制台 windows 中的ConsoleHost
。 [1]
Read-Host -AsSecureString
使用 GUI 對話框,而常規控制台 window 直接在控制台中提示。 我不知道您編譯的可執行文件(通過將 PowerShell 腳本包裝在獨立的可執行文件中創建)使用什么主機實現。 在最簡單的情況下,它使用簡單的DefaultHost
實現,當您通過PowerShell SDK 在應用程序中嵌入 PowerShell 時,默認使用該實現。
您所經歷的行為聞起來像一個錯誤,但至少上面顯示的解決方法似乎是有效的。
[1] 請注意,似乎無法通過自動$Host
變量確定特定於主機的PSHost
派生的 class 的完整類型名稱,其自身類型是非公共的
[System.Management.Automation.Internal.Host.InternalHost]` class。 類似地,特定於主機的類型可能是非公開的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.