Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do you do the equivalent of using a remote server's $env namespace without hardcoding network paths for cmdlets like Set-Location? I have a script that loops through remote servers and I'm trying to access their equivalent of $env:programfiles from a single script, but these servers have the variable set in different locations.

Basically getting a loop that navigates

c:\program files
\\server1\c$\program files

Using something familiar and simple like

Set-Location "${env:programfiles}"

And have the remote server's $env return a network path instead of a drive letter. The current way I'm doing it is grabbing the paths using Invoke-Command and building the path manually (replace : with $, append \\server in front of the path, turning "c:\program files" to "\\server\c$\program files")

share|improve this question
up vote 1 down vote accepted

This might be a little less complicated, and can easily be thrown into a foreach loop to work through your list of servers.

$RemoteServer = "KRINGER"
#The credential is required if you are working in a Workgroup 
#environment or your domain account does not have permissions
$value = Invoke-Command -ComputerName $RemoteServer -ScriptBlock {$Env:ProgramFiles} -Credential (Get-Credential) | % {$_ -replace ":","$"}

$RemoteWorkingPath = "\\" + $RemoteServer + "\" + $value + "\"
Write-Host "My remote path to use is: $RemoteWorkingPath"

Here is screenshot of the output: enter image description here

share|improve this answer

Try this:

function Get-RemoteProgramFilePaths {
    param ([string] $ComputerName)

    try {
        $hive = [Microsoft.Win32.RegistryHive]::LocalMachine
        $remoteRoot = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hive, $ComputerName)
        $key = $remoteRoot.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion')
        $key.GetValueNames() | ? {$_.StartsWith('ProgramFilesDir')} | % {
            return New-Object -TypeName PSObject -Property @{
                Name = $_
                Value = $key.GetValue($_)
    } catch {
        throw 'Failed to get remote program file paths. The error was: "{0}".' -f $_

Get-RemoteProgramFilePaths studio
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.