Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
\\server2\c$\programs
\\server3\d$\apps

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

2 Answers 2

up vote 0 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

 
discard

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.