SteinTech
SteinTech

Reputation: 4068

how to make a Powershell script avaiable from anywhere

I have a Powershell script I would like to make "public", meaning I want to be able to execute the script from any folder as you can do from the command prompt.

Is this possible?

Upvotes: 7

Views: 5229

Answers (4)

Starnuto di topo
Starnuto di topo

Reputation: 3569

You can use the Set-Alias cmdlet:

Set-Alias -Name 'list' -Value 'Get-ChildItem

This will make your alias available only for the current Powershell session.

To make your alias available across Powershell sections, add it to your $PROFILE file, either by editing it, or using a command like:

Add-Content -Path $PROFILE -Value "`nSet-Alias -Name 'list' -Value 'Get-ChildItem'"

In your $PROFILE file you can also define a function to run multiple commands:

function GoToMyPrivateDocuments {
    D:; cd mpd;
}
Set-Alias mpd GoToMyPrivateDocuments

Upvotes: 2

risail
risail

Reputation: 537

Name the script something meaningful ie: awesome.bat Save it in a dir and add the dir to windows env. Command awesome will be globally available.

Upvotes: 0

Jon Eakins
Jon Eakins

Reputation: 79

You can also add an alias in your local powershell profile

Alias Example in profile

Set-Alias hello C:\scriptlocation\script.ps1

Now anytime you type hello, the script.ps1 will run.

More info on the various profiles that the alias can be saved to. https://devblogs.microsoft.com/scripting/understanding-the-six-powershell-profiles/

Upvotes: 7

Josh Desmond
Josh Desmond

Reputation: 690

You can explore the use of your powershell profile to achieve this. See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles.

If the script is just a function or some variables, you can copy and paste the content into your profile.

Alternatively, if the script represents a standalone unit of code you want to keep separate, you could import it into your main profile as such:

get-content -path C:\blahblahblah\scriptName.ps1 -raw | invoke-expression

Finally, if you are writing an "advanced" powershell function, or are trying to do things officially, you could investigate the use of powershell modules as a way to export your function. See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_modules

@Lee_Dailey's answer of adding the script to your path is also viable. If you want to add a lot of scripts, one way to do that is to add a folder like C:/PowershellScripts/, to your path, save your scripts there, and then you'll be able to invoke your .PS1 file from anywhere.

Upvotes: 2

Related Questions