I need a way to expand environment variable on a remote machine.
Suppose I have a path to a folder %appdata%\MyApp\Plugins
or %ProgramFiles%\MyCompany\MyApp\Plugins
and I want to list files in that folder for audit purposes. The only problem is I want to do it on a remote machine, which however I have admin access to.
An extra question (but not essential) is how to do that for given user on remote machine?
Environment variables are the amalgamation of 'puter-wide and per-user settings. A running process may modify its environment and when it spawns another process, that process inherits the environment of the process that created it.
Unless you have access to a process running on the remote machine (or can start one), there's no such thing as an 'environment': the context for it simply doesn't exist. The environment of a particular process is a function of all of the following:
That being said, Windows keeps its environment variable settings in the registry:
HKEY_CURRENT_USER\Environment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
If you have appropriate access to the remote machine's registry, you should be able to fish out what you need.
Note that environment variables may be defined in terms of other environment variables: I believe you'll likely to take care of the proper expansion yourself.
The question doesn't make sense. Environment variables are not per-machine variables. For instance, you can expect
%appdata%
to point inside theC:\users\
directory, but precisely where obviously depends to the user. Logging in as admin still doesn't help you; that would merely tell you where the admin's%appdata%
is.You would use GetFolderPath. There are a bunch of different SpecialFolder values that you could use including
ProgramFiles
andApplicationData
Then you could just combine it with the rest of your path
On a remote machine, it looks like you can try something like this
Or for a list of all remote environment variables and their values, from here
OP Edit: Also
%AppData%
can be found from registry (can be done remotely) atHKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
and Program Files atHKLM\Software\Microsoft\Windows\CurrentVersion
, underProgramfilesDir
.As far as I can tell, the only way of resolving %ProgramFiles% is via the registry, since this is not exposed in Win32_Environment (despite the documentation suggesting otherwise). So this works fine:
However, I can't appear to use this approach to get back the Program Files (x86) folder - the key I can see in the registry doesn't 'show' using the registry API. Strange.
Of course if you were running Powershell Remoting on the remote machine, I imagine this would be fairly easy...