wget not found by PowerShell script?

2019-08-27 23:15发布

问题:

I have an old notebook with Windows 7 64-bit that executes a PowerShell script perfectly every Sunday. Unfortunately it starts to crash as soon as the load increases and I decided to get a new PC. On this PC I previously installed Windows e;10 Pro 64-bit and even here the script was executed every Sunday. Due to the update policy of Microsoft I removed Windows 10 from the new PC and installed Windows 7 64-bit. But now the same script crashes as it does not find wget:

$wg = Start-Process wget.exe -wait -NoNewWindow -PassThru -ArgumentList $argList 

Gnu Wget is installed correctly (I think). It is placed at:

C:\Program Files (x86)\GnuWin32\bin\wget.exe

It is even entered in the registry under HKEY_LOCAL_MACHINE → SOFTWARE → Wow6432Node → GnuWin32|Wget|1.11.4-1|setup|InstallPath: C:\Program Files (x86)\GnuWin32.

But despite this if I open the CMD console and enter wget (or wget.exe) I get:

The order "wget" is either misspelled or could not be found.

What do I have to do that PowerShell finds wget constantly even after a restart of the PC? Even e.g. Notepad++ cannot be found by the CMD console despite it is installed properly(?). What's wrong here?

回答1:

If you want to be able to run a command without specifying its path you need to add the directory it resides in to the PATH environment variable. The install path in the SOFTWARE branch of the registry has nothing to do with it.

To add a directory to the PATH for the current and all future sessions you need to do something like this:

$dir = "${env:ProgramFiles(x86)}\GnuWin32\bin"

# set PATH environment variable for current session
$env:Path += ";${dir}"

# set PATH environment variable for future sessions
$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
$path += ";{$dir}"
[Environment]::SetEnvironmentVariable('PATH', $path, 'Machine')

Note, however, that the second step (setting the variable for future sessions) only works correctly if there are no Windows environment variables (%something%) used in $path, because the method saves the value as a REG_SZ in the registry. Windows only expands environment variables in the PATH variable if it's stored as a REG_EXPAND_SZ value.

If you do have regular Windows environment variables somewhere in $path you must manually write the value to the registry with the correct type.

$key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
Set-ItemProperty -Path $key -Name 'Path' -Value $path -Type ExpandString

Addendum:

All of the above applies only if you want to do this programmatically, of course. For a manual approach you can always edit the environment variables via the GUI and restart PowerShell.