【问题标题】:Correct way to access the USERPROFILE dir of a specific user in a script?在脚本中访问特定用户的 USERPROFILE 目录的正确方法?
【发布时间】:2022-11-02 23:47:37
【问题描述】:

我正在编写一个脚本来在 Windows 机器上的每个(本地)用户的 USERPROFILE 文件夹中执行一些文件操作。

我发现了各种使用$env:USERPROFILE 来识别当前登录用户的配置文件目录的示例。我还看到了假设所有用户配置文件都保存在 C:\Users\ 并迭代/过滤该文件夹的示例。

但是,可以在 Windows 上移动配置文件文件夹。我的目标是(可靠地)找到特定用户的配置文件目录,给定该用户的用户名(字符串)或 LocalUser 对象。

我可以根据活动帐户获取一组用户对象 -

$users = Get-LocalUser | Where-Object Enabled -eq true

但是那些 LocalUser 对象的属性是有限的,UserProfile 路径不在其中。我相信这些信息存储在注册表中。我已经多次阅读 PowerShell 文档,但我还没有找到正确的咒语,可以为我提供给定用户的用户配置文件的路径,我可以在循环中使用它来遍历所有用户及其配置文件文件夹。

【问题讨论】:

    标签: powershell profile


    【解决方案1】:

    您可以检索根(父)目录所有用户配置文件目录从注册表如下:

    $profilesRootDir = 
      Get-ItemPropertyValue 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList' ProfilesDirectory
    

    要得到一个特定用户的个人资料目录,比如说jdoe,然后你可以使用:

    # See more robust alternative below.
    Join-Path $profilesRootDir jdoe
    

    但是,那事实的最终来源是ProfileImagePath 值子键上述注册表项路径,为每个用户命名SID(安全标识符),其中Get-LocalUser 做提供(输出对象具有.SID 属性)。

    因此,它是更好的使用:

    Get-ItemPropertyValue "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList$((Get-LocalUser jdoe).SID)" ProfileImagePath
    

    为了可靠地得到个人资料目录全部启用本地用户,使用以下内容:

    Get-LocalUser | 
      Where-Object Enabled |
      ForEach-Object {
        # Note the use of ...ProfileList$($_.SID) and value name ProfileImagePath
        Get-ItemPropertyValue "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList$($_.SID)" ProfileImagePath
      }
    

    【讨论】:

      【解决方案2】:

      也许沿着这条线:

      $users = Get-LocalUser | Where-Object Enabled -eq true
      
      $profilesRootDir = @(
       Get-ItemPropertyValue 'HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList' ProfilesDirectory)
      
      ForEach ($User in $Users) {
      
        $UserPath = Join-Path -Path "$profilesRootDir" -ChildPath "$User"
      
        "User     : $User`n" +
        "User-Path: $UserPath" 
      }
      

      输出:

      User     : Bruce
      User-Path: C:UsersBruce
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-22
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        相关资源
        最近更新 更多