Create and use a PowerShell console file

When writing scripts, sooner or later you will realize that you add the same snap ins all over again in different scripts.

What you can do in this case is to export all loaded PowerShell snap ins from a console to a file that can be loaded when starting PowerShell. This way, your scripts doesn’t need to have 10 lines where you load them in all your scripts.

One thing I’ve noticed, is that some snap ins can’t be loaded in the script if the script is to be run in a scheduled task. In my case it was the snap in for Exchange 2013, if the snap in was loaded in the script, an exception was thrown, but as soon as I created the console file with the snap in loaded, it worked the way it was superposed to!

To export the console, simply type the following line:
Export-Console -Path C:\Script\Console.psc1

This will save the current console and when needed, you cant start powershell.exe with the -PSConsoleFile switch. In this case the complete line will be:
powershell.exe -PSConsoleFile C:\Script\Console.psc1

When exporting the console, you have two other options for the -Path parameter. If you just specify a file name, for example “Console1.psc1” the file will be created in the current folder. If you do not use the -Path parameter at all, PowerShell will overwrite the console file that was created most recently.
The file name for this is stored in the variable $ConsoleFileName

 

This entry was posted in Powershell and tagged , , , , , . Bookmark the permalink.

2 Responses to Create and use a PowerShell console file

Leave a Reply

Your email address will not be published. Required fields are marked *