Glossary:
- Host: PowershellHost session
- Interactive:
[Environment]::UserInteractive -eq $True
Scenario:
Create a powershell module that only will abort propertly and without error on failed condition. In this case, some commands/modules only work properly in full interactive hosts, like ISE and Console, but not in fake interactive hosts like NuGet Package Manager Console
Failed Solution:
# 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 = ''
....
}
Failed Solution:
# 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
}
Failed Solution:
# 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
}
Failed Solution:
# Issue: Module isn't loaded, so it can't be unloaded
if( $Host.Name -inotmatch '(ConsoleHost|Windows PowerShell ISE Host)' ) {
Remove-Module ThisModuleName
}
Failed Solution:
# 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
}
Annoying solution:
# 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"
}
Not a solution:
Force user to wrap the import every time.
Questionable Solution:
Split module into nested submodules, one for 'Common', and one for each supported Host. Use subfolder for each, and duplicate psd1 for each. Looks like it will end up being a maintainability nightmare, especially with respect to nested dependencies.
UberModule
/ModuleCommon
/ModuleCommon.(psd1|psm1)
/ConsoleHostSpecific
/ConsoleHostSpecific.(psd1|psm1)
/IseHostSpecific
/IseHostSpecific.(psd1|psm1)
/etc...
Is there a better way to do this, or is the uber-module split the only way to go?
Take a look at the
#requires
keyword, it may offer a few options that you have not tried yet. I don't know if NuGet Package Manager Console has a unique ShellId or not.http://technet.microsoft.com/en-us/library/hh847765.aspx