开发者

Can a powershell module unload itself

I am writing a powershell script module. One of the first things it does is some checks to make sure certain required values are available. If not, the module should not continue to load and initialize. However, I'm not aware of a way for a module to "remove" itself. I tried calling remove-module (from within the module) but not surprisingly it did not work. Is there some other way to have a module unload itself?

I realize this would be trivial to do from a script that is outside the module. But I'm writing this module to be shared with other users who are not very savvy re powershell. I would like to not have to include the module PLUS another script and then explain to them that "this i开发者_开发技巧s an exception and you can't use the normal import-module, you have to always remember to find and run this other script instead". Besides that, it wouldn't be helpful in case a user did simply use import-module (as they would reasonably expect to be able to do) instead of using an extra script.


You could throw an error in your module if the checks do not pass - this will stop the module from loading. For example try saving this as Test.psm1:

throw "Could not load module.";

Try loading this with Import-Module .\Test.psm1. You'll get the error and if you do a call to Get-Module afterwards you'll see the module has not been loaded.


It is not an exact answer to your question but it is still a solution. In scenarios like you describe I would go another way. Create an external script (not part of a module) that either checks prerequisites itself and does not load the module at all if something is missing or loads the module always, checks success/failure-something exposed by the module and unloads the module in case of a failure. Then use this script instead of Import-Module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜