0

I have a powershell script that I want to run from cmd/ps any location by putting it in path. What is the command that can achieve that ?

I m basically looking for a UNIX equivalent of putting your script in bashrc and thus available from anywhere to run.

echo 'export PATH=$PATH:/path/to/script' >> ~/.bashrc && source ~/.bashrc
1

1 Answer 1

1

In windows you also have the system variable PATH that's used for defining where to locate executables.

You could do the following that should be equivalent assuming you're only using Powershell:

$newPath = "c:\tmp\MyScriptPath"; 
[Environment]::SetEnvironmentVariable('PATH', "$($env:Path);$newPath", [EnvironmentVariableTarget]::User);
# Update the path variable in your current session; next time it's loaded directly 
$env:Path = "$($env:Path);$newPath";

You can then execute your script directly in Powershell with just the name of the script.

However_ : this will not work under cmd because cmd doesn't know how to handle the ps1 script as an executable. Normally one would execute the script from cmd by calling the following:

 Powershell.exe -executionpolicy remotesigned -File  C:\Tmp\Script.ps1 

If this is "unacceptable" for you, the easiest way is to create a bat script along with your ps1 script (same path) and add the following content :

Script.bat (Assuming you have Script.ps1 in the same folder):

@ECHO OFF
PowerShell.exe -Command "& '%~dpn0.ps1'"
PAUSE

This will create the wrapper needed to Invoke Script anywhere in your cmd as batch files can be executed from cmd

Sign up to request clarification or add additional context in comments.

1 Comment

Tried the bat file route but it complains :powershell.exe : The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file,...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.