如何使用远程服务器的$ env命名空间,而不使用Set-Location等cmdlet的networkingpath硬编码? 我有一个通过远程服务器循环的脚本,我试图从一个脚本访问它们的$ env:programfiles等价物,但是这些服务器在不同的位置设置了variables。
基本上得到一个循环,导航
c:\program files \\server1\c$\program files \\server2\c$\programs \\server3\d$\apps
用一些熟悉而简单的东西
Set-Location "${env:programfiles}"
并且让远程服务器的$ env返回一个networkingpath而不是一个盘符。 目前我这样做的方法是使用Invoke-Command获取path并手动构buildpath(用$replace,在path前面追加\\服务器,将“c:\ program files”变成“\\ server \ c $ \ program files“)
这可能不太复杂,可以很容易地引入到foreach循环来处理您的服务器列表。
$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"
这里是输出的截图: 
尝试这个:
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