formats

PowerShell Startup Auto-Load Scripts

Published on August 21, 2011

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.

  1. Tools Dir & Env Var
    I keep a general
    Tools
    directory on my machine with command line tools, scripts, etc and so set a system environment variable called
    tools
    that points to this directory.
  2. Run Unsigned Scripts
    Run
    set-executionpolicy bypass
    once in each environment (cmd shell and ISE) to allow easy execution of unsigned scripts.
  3. 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.
  4. 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.
  5. 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
    :
  6. # 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"  
  7. 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.  :)

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Noah Coad
credit