我的foreach循环有什么问题?

时间:2016-01-20 21:06:00

标签: .net powershell scripting command

我编写了这个foreach循环,将所有用户添加到本地管理员组中,除了一些条件。它似乎通过前两个if语句很好,但是当涉及到将用户添加到管理组的部分时,我得到错误“该组已经存在”。有任何想法吗?

$UserList = Net User

foreach ($User in $UserList)
{
    if($User -match "Lcs")
    {
        Write-Host "FCS Account Excluded."
    }

    if($User -match "Guest" -Or $User -match "Administrator")
    {
        Write-Host "Default Windows Accounts Excluded."
    }
    else 
    {
        net localgroup Administrators $User /Add
    }
}

2 个答案:

答案 0 :(得分:1)

问题在于Net User存储用户的方式。

尝试以下块:

$UserList = Get-WmiObject -Class Win32_UserAccount  -Filter "LocalAccount='True'"
foreach ($User in $UserList)
{
    if($User.Name -match "Lcs")
    {
        Write-Host "FCS Account Excluded."
    }
    elseif ($User.Name -match "Guest" -Or $User.Name -match "Administrator")
    {
        Write-Host "Default Windows Accounts Excluded."
    }
    else 
    {
        net localgroup Administrators $User.Name /Add
    }
}

此外,我建议不要使用Net local group administrators user.add,因为它正在使用其他应用网,但使用它没有任何问题。

答案 1 :(得分:1)

net user命令的输出如下所示:

PS C:\> net user

User accounts for \\ComputerName

-------------------------------------------------------------------------------
user01               user02               user03               user04
user05               user06
The command completed successfully

PS C:\>

请注意,如果您只对用户名感兴趣,前4行是无用的,最后两行也是如此。您可以使用Select-Object -SkipSelect-Object -First

删除它们
PS C:\> $netuser = net user |Select-Object -Skip 4
PS C:\> $netuser |Select-Object -First $($netuser.Length - 3)
user01               user02               user03               user04
user05               user06
PS C:\>

现在您只需将用户名拆分为单个字符串:

PS C:\> $users = $netuser |Select-Object -First $($netuser.Length - 3) |ForEach-Object {
    $_.Split(' ',[StringSplitOptions]::RemoveEmptyEntries)
}
PS C:\> $users
user01
user02
user03
user04
user05
user06