[英]Script runs with ISE but not via PowerShell console
我有一個腳本可以在 ISE 上順利運行,但在通過 PowerShell 控制台運行時會停止。 引發的錯誤:
您不能在空值表達式上調用方法
所以這里是代碼示例(不能全部顯示):
$global:mainForm.Text= $global:mainForm.text.substring(0,$global:mainFormTitleSize)+" || Save File Name = ..."+$outputFileName.substring($outputFileName.length - $decalage,$decalage)
我用調試運行 ISE 來檢查每個變量,但一切都不是 null。 但是當我通過 PowerShell 控制台執行時,屬性$global:mainForm.Text
為空。 即使它在上面設置了幾行並且從未在兩者之間觸及。
編輯:通過更多的挖掘,我注意到mainForm
沒有被聲明為$global:
而是作為一個簡單的變量。
這可能是問題的一部分嗎? (我對 ps 很陌生,這不是我的腳本,所以我不知道會發生什么)
都靈,
ISE 會自動加載 Shell 不會自動加載的一些程序集。 我在所有使用 forms 的代碼中包含以下代碼,以確保無論在何處運行它都能正常工作。
Add-Type -AssemblyName "System.Windows.Forms"
If ($host.Name -eq 'ConsoleHost' -or
$host.Name -eq 'Visual Studio Code Host') {
try{ <#+------------------------------------------------+
| Check that the proper assemblies are loaded |
| for using XAML forms. |
| Required for PS Console and Visual Code, while |
| only Systems.Windows.Forms needed for PSISE! |
+------------------------------------------------+
#>
$ATArgs = @{AssemblyName = "PresentationCore",
"PresentationFramework",
"WindowsBase"
ErrorAction = 'Stop'}
Add-Type @ATArgs
}
catch {
$Message =
"Failed to load Windows Presentation Framework" +
" and/or other assemblies required for this program!"
& $TermMsg
Exit
}
} #End If ($host...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.