I was just reading Steve Murawski’s latest blog post which contains a script called ConvertTo-Function that allows you to generate a function from a script file. The intent is to allow you to have scripts you don’t call as often, and therefore don’t load into your profile, but when you need them you can use this script to easily generate functions that wrap them so that you don’t need to think about the path beyond the initial call to the ConvertTo-Function script. That’s one way to facilitate this, but I have something I use quite commonly in my own environment that works much better for me for this scenario: aliases.
Aliases can reference a path to a script file.
This capability is often overlooked because aliases are most commonly used and thought of as terse command names. Using them to reference a path to a script file is quite useful because it allows you to keep all of your scripts, complete or in development, in a common location. You can control which ones are loaded in your profile by only creating aliases for those scripts. Alternatively, for scripts that you really don’t use very often, you could have a function in your profile to create the aliases to those scripts on an as needed basis (which sounds a little like the Add-Module capabilities in PowerShell v2). In either case, using aliases to reference script files is very handy because you don’t need to worry about whether the scripts you want to invoke are in a folder in your path environment variable or not. You simply need to create an alias to the full path and then you can use that alias to invoke your script.
For example, assuming you had a script with the path C:\MyScripts\Miscellaneous\Do-Something.ps1, you could invoke it using the absolute or relative path, or if C:\MyScripts\Miscellaneous happened to be in your path environment variable you could simply invoke it using the Do-Something command. But if you don’t have your script path in your path environment variable and/or you don’t want to change that variable, aliases give you the same capability on a temporary basis for your current PowerShell session (and only in your current scope by default if you want it really temporary). Using our example script path, all you would have to do is create a new alias with this command:
New-Alias Do-Something C:\MyScripts\Miscellaneous\Do-Something.ps1
That allows you to invoke your script any time you want to by simply using the Do-Something alias, as long as it is created and visible in the current scope.
|Share this post:|