windows - Powershell存在本地用户ADSI

标签 windows powershell local

我得到了以下代码(工作):

   #Import File
$Users = Import-Csv C:\Users\Administrator\Desktop\userImport\users.csv

# Setting data
$compname = hostname
$computer = [ADSI]"WinNT://$compname" 
$userGroup = [ADSI]"WinNT://./Users,Group"

# Loop to add all users
$Users | %  { 

    # Create user itself
    $createUser = $computer.Create("User",$_.userid)

    # Set password (print1!)
    $createUser.SetPassword($_.password)
    $createUser.SetInfo()

    # Create extra data
    $createUser.Description = "Import via powershell"
    $createUser.FullName = $_.'full name'
    $createUser.SetInfo()

    # Set standard flags (Password expire / Password change / Account disabled)
    $createUser.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
    $createUser.SetInfo()

    # Adduser to standard user group ("SERVER02\Users")
    $userGroup.Add($createUser.Path)

    # Show that user X as been added
    $username = $_.'full name'
    echo "User  $username added"
}

但是如何检查用户是否已经存在呢? 我在网上找不到任何东西:x

最佳答案

你可以试试这个:

   #Import File
$Users = Import-Csv C:\Users\Administrator\Desktop\userImport\users.csv

# Setting data
$compname = hostname
$computer = [ADSI]"WinNT://$compname" 
$userGroup = [ADSI]"WinNT://./Users,Group"

$localUsers = $computer.Children | where {$_.SchemaClassName -eq 'user'}  |  % {$_.name[0].ToString()}

# Loop to add all users
$Users | %  { 

    if($localUsers -NotContains $_.userID)
    {
      ... do your job here....
    }
    else
    {
      write-host "User $($_.userID) already exists"
    }
}

关于windows - Powershell存在本地用户ADSI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13685456/

相关文章:

c# - Windows 通用应用程序 - 从应用程序启动 CMD

python - 未绑定(bind)本地错误 : local variable referenced before assignment (Python)

windows - 如何获取连接显示器的 GPU 卡列表?

c++ - 使用带文字的 SysAllocString 有什么问题吗?

powershell - 限制在 powershell 中运行的 Start-Process 数量

powershell - 从文件名中删除无关的字符

azure - Oauth 身份验证 token 在 powershell 中失败,但在 Postman 中失败

C++ 使用同名变量/对象访问命名空间中的全局变量/对象

c++ - 未初始化的局部变量

windows - 如何从管理进程以当前用户权限运行进程