It’s very handy to have a PowerShell script automatically load when PowerShell starts up to configure your environment, like an AutoExec.bat in the old DOS days. Here’s how I have mine set up.
- Tools Dir & Env Var
I keep a general
directory on my machine with command line tools, scripts, etc and so set a system environment variable called
that points to this directory.
- Run Unsigned Scripts
Run
set-executionpolicy bypass
once in each environment (cmd shell and ISE) to allow easy execution of unsigned scripts.
- Profiles Auto-Load Script
PowerShell supports profiles with an auto-load script on PowerShell start up. Simply put the files
Microsoft.PowerShell_profile.ps1
(for basic shell) and
Microsoft.PowerShellISE_profile.ps1
(for the GUI) in your
%UserProfile%\Documents\WindowsPowerShell
directory. These will be run on PowerShell startup.
- Consolidate Scripts
The only line I have in these files is:
."${env:tools}\PSScripts\PowerShellEnvironment.ps1"
to launch my ‘real’ script. This make it easier to manage, with only one file that’s near my other powershell scripts instead of the two separate scripts above.
- Chain ‘autoload’ Scripts
Then it helps to separate into individual scripts various aspects of your environment setup. Like a script for aliases, itunes, functions, regular expressions, favorite assemblies, etc. So I have an ‘autoload’ directory with these scripts in them to chain load. Here are the contents of
PowerShellEnvironment.ps1
:
# directory where my scripts are stored
$psdir="${env:tools}\PSScripts"
# load all 'autoload' scripts
get-childitem "${psdir}\autoload\*.ps1" | %{.$_}
Write-Host "Custom PowerShell Environment Loaded"
- My ‘autoload’ Scripts
Here is a snapshot of my autoload directory of scripts in case you’d be interested. PowerShellScripts-autoload.7z
That’s all there is to it. One of the reasons for putting this out there is so that I can now reference it from other posts too. :)