如何执行与使用远程服务器的 $env 命名空间相同的操作,而无需对 Set-Location 等 cmdlet 的网络路径进行硬编码?我有一个循环遍历远程服务器的脚本,我试图从单个脚本访问它们的等效项 $env:programfiles,但这些服务器在不同的位置设置了变量。
基本上得到一个导航循环
c:\program files
\\server1\c$\program files
\\server2\c$\programs
\\server3\d$\apps
使用一些熟悉而简单的东西,例如
Set-Location "${env:programfiles}"
并让远程服务器的 $env 返回网络路径而不是驱动器号。我目前的做法是使用 Invoke-Command 获取路径并手动构建路径(将 : 替换为 $,在路径前面附加 \\server,将“c:\program files”改为“\\server\c$\program files”)
答案1
这可能稍微不太复杂,并且可以轻松地放入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"
以下是输出的屏幕截图:
答案2
尝试这个:
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