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?
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.
You could do:
Set-Alias Get-Filehash "E:\Tools\Power Shell Scripts\Get-FileHash.ps1"
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With