如何只为特定的少数用户获取 $userPath

how to fetch $userPath for only specific few users

使用下面的 poweshell 脚本,我可以看到所有用户配置文件的 userpath

# Get a list of all user profiles
$users = Get-WmiObject Win32_UserProfile

foreach( $user in $users ) {

# Normalize profile name.
$userPath = (Split-Path $user.LocalPath -Leaf).ToLower()

Write-Host $userPath

}

如何用特定的 2 个用户过滤这个,比如 user1user2

您可以通过参数filter和WQL查询过滤WMI返回的结果。

试试这个代码

$users = Get-WmiObject win32_userprofile -filter 'LocalPath LIKE "%user1%" OR LocalPath LIKE "%user2%"'

foreach( $user in $users ) {

    # Normalize profile name.
    $userPath = (Split-Path $user.LocalPath -Leaf).ToLower()
    Write-Host $userPath
}

请参阅 MS documentation for Get-WmiObject 并查找 Filter 参数

你是说这个...

# Get a list of all user profiles
$users = Get-WmiObject Win32_UserProfile


foreach( $user in $users ) 
{ (Split-Path $user.LocalPath -Leaf).ToLower() }

# Results
<#
...
networkservice
localservice
systemprofile
#>

# Get a list of specific user profiles
foreach( $user in $users ) 
{ (Split-Path $user.LocalPath -Leaf).ToLower() | Select-String 'networkservice|localservice' }

# Results
<#
networkservice
localservice
#>

或one-liner

 (Split-Path (Get-WmiObject Win32_UserProfile | 
 Where-Object -Property LocalPath -match  'networkservice|localservice').LocalPath -Leaf).ToLower()

# Results
<#
networkservice
localservice
#>