从远程机器获取特殊文件夹

Getting special folder from remote machine

有没有办法从远程计算机获取特殊文件夹?

我正在使用此代码获取本地文件夹:

$path = [environment]::getfolderpath("CommonApplicationData")

但我想使用如下函数从其他机器获取它:

$specialFolder = Get-RemoteSpecialFolder "MyRemoteMachine" "CommonApplicationData"

function Get-RemoteSpecialFolder
{
    param( 
        [string]$ComputerName,
        [string]$SpecialFolderName
    )
    Get-WMIObject ...
    ...
}

您可以通过读取远程计算机注册表(当然您需要权限)来获取此信息,就像下面的函数一样:

function Get-RemoteSpecialFolder {
    [CmdletBinding()]
    param(
        [string]$ComputerName = $env:COMPUTERNAME,

        [string]$SpecialFolderName = 'Common AppData'
    )
    if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
        $regPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
        try {
            $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
            $regKey  = $baseKey.OpenSubKey($regPath)
            return $regkey.GetValue($SpecialFolderName)
        }
        catch {
            throw
        }
        finally {
            if ($regKey)  { $regKey.Close() }
            if ($baseKey) { $baseKey.Close() }
        }
    }
    else {
        Write-Warning "Computer '$ComputerName' is off-line or does not exist."
    }
}

你应该能够找到这些常见的环境变量:

"Common Desktop"
"Common Start Menu"
"CommonVideo"
"CommonPictures"
"Common Programs"
"CommonMusic"
"Common Administrative Tools"
"Common Startup"
"Common Documents"
"OEM Links"
"Common Templates"
"Common AppData"

P.S。先放函数,再调用

$specialFolder = Get-RemoteSpecialFolder "MyRemoteMachine" "Common AppData"