从远程计算机获取特殊文件夹

时间:2019-06-21 10:55:41

标签: powershell get-wmiobject

是否可以从远程计算机获取特殊文件夹?

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

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

但是我想使用这样的功能从其他机器上获取它:

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

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

1 个答案:

答案 0 :(得分:3)

您可以通过阅读远程计算机注册表(当然需要权限)来获取此信息,如以下功能所示:

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"
相关问题