1
- 主持人:PowershellHost會議
- 互動:
[Environment]::UserInteractive -eq $True
場景:
創建一個PowerShell模塊,只有將propertly中止和在失敗的情況下沒有錯誤。在這種情況下,一些命令/模塊只有正確全面互動主機像NuGet包管理器控制檯假互動主機的工作,像ISE和控制檯,但不
失敗解決方法:
# Add value to Powershell manifest(psd1)
# Issue: Only supports a string for the `PowerShellHostName` property. How to specify both `ConsoleHost` and `Windows PowerShell ISE Host`? Unknown if this property supports regex, and even if it does, will the behavior change since it's not documented?
@{
....
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
....
}
失敗解決方法:
# Check for interactive shell
# Issue: UserInteractive is still set in embedded shells like NuGet package manager
# console. Commands that expect user input directly often hang.
if([Environment]::UserInteractive) {
# Do stuff, dotsource, etc
}
失敗解決方法:
# Issue: returning still leaves module loaded, and it appears in Get-Module list
# Even if value is supplied for return, powershell's return statement is 'special'
# and the value is ignored
if($Host.Name -inotmatch '(ConsoleHost|Windows PowerShell ISE Host)') {
Write-Warning "Host [$($Host.Name)] not supported, aborting"
return
}
失敗解決方案:
# Issue: Module isn't loaded, so it can't be unloaded
if($Host.Name -inotmatch '(ConsoleHost|Windows PowerShell ISE Host)') {
Remove-Module ThisModuleName
}
失敗解決方法:
# Issue: Powershell module error output is just passthrough, import-module
# still reports success, even though $Error is has more stuff than before
if($Host.Name -inotmatch '(ConsoleHost|Windows PowerShell ISE Host)') {
Write-Error "Unsupported Host:" $Host.Name
}
惱人的溶液:
# Issue: Leaves two errors on the stack, one for the throw, one for the module not
# loading successfully
if($Host.Name -inotmatch '(ConsoleHost|Windows PowerShell ISE Host)') {
throw "Host [$($Host.Name)] not supported, aborting"
}
不是一個解決方案:
Force user to wrap the import every time.
可疑解決方案:
將模塊拆分爲嵌套子模塊,一個用於'Common',另一個用於每個受支持的主機。爲每個文件夾使用子文件夾,併爲每個文件夾複製psd1。看起來它最終會成爲可維護性的噩夢,尤其是對於嵌套的依賴關係。
UberModule
/ModuleCommon
/ModuleCommon.(psd1|psm1)
/ConsoleHostSpecific
/ConsoleHostSpecific.(psd1|psm1)
/IseHostSpecific
/IseHostSpecific.(psd1|psm1)
/etc...
有沒有更好的方法來做到這一點,還是超級模塊拆分的唯一途徑?