Load powershell script to be callable at any time

16,632

Solution 1

Actually, the best practice in this situation is to put the function in a module rather than in a script. As ominous as that sounds, all it means is rename the containing file from a .ps1 extension to a .psm1 extension and then store it under your Documents directory (...\Documents\WindowsPowerShell\Modules\<Name>\<Name>.psm1) where <Name> is the base name of your file.

You then load the module with this command:

Import-Module Name

Once loaded, you can call the functions contained within the module and Get-Help will recognize the commands as well. Among other things, modules provide encapsulation so one file does not pollute the context space of another. And by the way, you do not need to write cmdlets in C#; you can also write them in PowerShell itself. By way of example, take a look at my open-source PowerShell library which is all written in PowerShell and includes plenty of help recognized by Get-Help.

There is a lot more to know to really get the full benefit of using functions and modules--I refer you to my article Down the Rabbit Hole-A Study in PowerShell Pipelines, Functions, and Parameters on Simple-Talk.com.

Solution 2

You could do:

Set-Alias Get-Filehash "E:\Tools\Power Shell Scripts\Get-FileHash.ps1"

Solution 3

Put the directory in which your script resides on your executable PATH (i.e. the PATH environment variable).

BTW, your function wrapper work-around doesn't work because you are not passing the argument to the script:

function Get-FileHash {. 'E:\Tools\Power Shell Scripts\Get-FileHash.ps1' $args}

or you could create an alias (as suggested in other answers)

Share:
16,632
Scott Chamberlain
Author by

Scott Chamberlain

Any opinions expressed here are my own and not that of Amazon nor any of it's subsidiaries.

Updated on June 21, 2022

Comments

  • Scott Chamberlain
    Scott Chamberlain almost 2 years

    I am new to powershell and was trying to use the example script posted here (the script itself) to calculate a file hash. I can get it to work using dot notation

    . 'E:\Tools\Power Shell Scripts\Get-FileHash.ps1' E:\testfile.bin
    

    however I want to be able to use it like the author does and just type

    Get-Filehash E:\testfile.bin
    

    I have found I can do

    function Get-FileHash {. 'E:\Tools\Power Shell Scripts\Get-FileHash.ps1'}
    

    but that does not behave correctly, it prompts me for the file when I do Get-Filehash E:\testfile.bin

    What do I need to put in my profile script to correctly load this script and Get-Help Get-FileHash works correctly?