1

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.

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.

jpgerb
  • 1,043
  • 1
  • 9
  • 36

1 Answers1

1

This should solve your problem:

$newPath = 'c:\users\USERNAME\scripts'
$targetEnv = [System.EnvironmentVariableTarget]::User # or `::Machine`

[System.Environment]::SetEnvironmentVariable(
    'Path',
    @([System.Environment]::GetEnvironmentVariable('Path', $targetEnv).Split(
        [System.IO.Path]::PathSeparator,
        [System.StringSplitOptions]::RemoveEmptyEntries)
        $newPath) -join [System.IO.Path]::PathSeparator,
    $targetEnv)

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.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • 1
    Tried it with both `::User` and `::Machine` - neither work - same error when I try and run `beginPHP` – jpgerb Dec 13 '22 at 23:47
  • 1
    I lied - I'm an idiot - I wasn't restarting `PS` - restarted `PS` and it works perfectly. – jpgerb Dec 13 '22 at 23:49
  • 1
    @jpgerb yeah forgot to mention you need to restart your current session to have it available, my bad :P – Santiago Squarzon Dec 13 '22 at 23:50
  • 1
    What's sad is I knew that too - just totally forgot. Kind of glad I forgot if the $env:path would just reset anyway. At least now I have it in my SystemEnvVar – jpgerb Dec 13 '22 at 23:50