Windows – How to Add Scripts to Path

pathpowershellscriptwindows 8

I've stored commonly used powershell scripts at %USERPROFILE%\Bin. I created a USER_BIN environment variable which I added to the user PATH environment variable via Control Panel > System and Security > System > Advanced system setting > Environment Variables.

When I enter the name of a script stored in Bin, i.e. my-script.ps1, into a cmd or powershell prompt I get the message my-script.ps1 : The term 'my-script.ps1' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

If I provide the full-path, i.e. C:\Users\Ari\Bin\my-script.ps1 the script works fine.

Best Answer

  • It's a powershell security feature. You can only invoke scripts by relative or absolute path but not by file name.

    To run a script, type the path and name of the script file. The path is required, even when the script is located in the current directory, to make it more difficult for malicious code to run scripts. The file name extension is optional and, as always, Windows PowerShell is not case sensitive.

    The reasoning behind this decision is as follows:

    One trick malicious users commonly attempt in other shells is creating a script with the same file name as a built-in command. So, for example, if you wanted a user to run your script, you might name it Dir.ps1 and drop it into a folder. If you convinced the user to type Dir and press Enter, your script could run, not the Dir command the user was expecting. This technique is called command hijacking. In Windows PowerShell, you must always provide a path to such a script, making Windows PowerShell pretty well protected against command hijacking. Running demo1 doesn't work, since there's no path, but running ./demo1 does work. This is because I've now specified a path—the current folder. That command line is less likely to be confused with a built-in command since you'd never type any kind of path if you were referring to a built-in command. Thus, requiring a path helps Windows PowerShell avoid command hijacking and confusion over what might happen when you press Enter.