Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell – How to use a script without the path to work in the current path?

I apologize in advance, I’m not entirely sure the best way to word my question. Here’s what I’m trying to do…

I created a script called beginPHP.ps1 which is located in my c:\users\USERNAME\scripts directory.

I added said directory with $env:path += c:\users\USERNAME\scripts and it shows when I do $env:path. I also made sure it shows in my Environment Variables (and System Variables) per This Link.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I opened my PowerShell (v7) and went to the directory I wanted the script to RUN in (not where it’s located). In this case C:\xampp\htdocs\wip. Running the command beginPHP gives me the following error:

beginPHP: The term 'beginPHP' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Here’s what I’m looking for —
What am I missing in order to be able to just type in a script name and have it run at the current -Path?

I did check how-to-run-a-powershell-script, but that needs you in the location the script is located. I hope to use this script more than once in more than one location (or I wouldn’t bother creating it).

/*******************************************************/

FYI – running c:\users\USERNAME\scripts\beginPHP did work, so the script is functional. I’m still trying to figureo out how to NOT need the path everytime.

>Solution :

This should solve your problem:

$newPath = 'c:\users\USERNAME\scripts'

[System.Environment]::SetEnvironmentVariable(
    'Path',
    [System.Environment]::GetEnvironmentVariable('Path') + ';' + $newPath,
    [System.EnvironmentVariableTarget]::User # or `::Machine` up to you
)

The problem is that storing the path in $env:Path doesn’t persist across sessions. If you want it to persist, you can use [System.Environment]::SetEnvironmentVariable method. You could also consider turning your ps1 into a psm1 and using a Module instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading