Sunday, February 27, 2011

If you need to get some system variables remotely but you don't want to copy any file on the remote system (for example because you don't know which is the %systemdrive% there are a courple of ways to do that.

Psexec doesn't work with system variables on the remote computer, for example if you type psexec \\anothercomputer cmd /c echo %computername% it will echo hostname of from where you are running psexec.

You might have heard of owexec it will let you run the command you want using the credentials of a loggedon user on the remote computer.

But it's not exactly what I needed, I just need to get system variables and without any user being logged on the remote computer. Plus it uses WMI, and that could be a problem if your computer does have a policy not to allow it.

There is a much easier way to do this.System variables doesn't "work" (actually they work exactly like intended) because of the way the windows command line handles variable expansions. Imagine an environment with 2 PCs (PC1 in DOMAIN1 and PC2 in DOMAIN2) and the following at the command line of PC1:

psexec \\PC2 cmd /c echo %USERDOMAIN%

The system variable %USERDOMAIN% gets expanded before the echo command is sent to the remote host, resulting in the following being executed at the remote host PC2:

echo DOMAIN1

That's why it looks like it does not work.You need just 1 character to fix this:

psexec \\PC2 cmd /c echo %USERDOMAIN^%

The ^ character is the escape character of the windows command line. It prevents the interpreter at PC1 to expand the variable and lets the remote host PC2 execute what you want it to:

echo %USERDOMAIN%

That finally is parsed by the remote host's interpreter and you get the result you expected: