Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load powershell script to be callable at any time

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?

like image 649
Scott Chamberlain Avatar asked Feb 01 '12 23:02

Scott Chamberlain


3 Answers

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.

like image 177
Michael Sorens Avatar answered Oct 05 '22 14:10

Michael Sorens


You could do:

Set-Alias Get-Filehash "E:\Tools\Power Shell Scripts\Get-FileHash.ps1"
like image 25
Mike Christensen Avatar answered Oct 05 '22 13:10

Mike Christensen


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)

like image 40
zdan Avatar answered Oct 05 '22 13:10

zdan