<< A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

–A–

active directory users, save to CSV

Get-ADUser -Filter {mail -like "*" -and enabled -eq "true" -and Surname -like "*"} | Select-Object GivenName, Surname, Name, UserPrincipalName  | Export-Csv documents\ADusers4.csv

Notice this only gets users with

–B–

–C–

contacts, create from CSV

This example includes processing a "language" column which has special characters

$UserDomain = "yourDomain.com"
$OU = "OU=YourOU,DC=yourDomain,DC=com"
$dir = [environment]::getfolderpath("mydocuments") + "\"
$fileSuffix = ".csv"
$fileBase = "someFileName"
color:#CE9178'>"someFileName"
$file = $dir + $fileBase + $fileSuffix
$fileUTF8 = $dir + $fileBase + "_utf8" + $fileSuffix
$i=0
# to get special foreign characters, we must go through this bass-ackwards way of import/export/import below
# See https://www.ilikesharepoint.de/2015/02/powershell-import-data-from-csv-with-special-characters/
#Convert CSV to UTF-8 with special characters
Get-Content $file | Out-File $fileUTF8 -Encoding utf8
# Only now can we import using Unicode
$csv = Import-CSV $fileUTF8 -Encoding Unicode
foreach($item in $csv)
{
    $i++
    if (($null -eq $item.LastName) -or ($item.LastName -eq '')){break} # some files have lots of empty junk rows at the end
    $FirstName = $item.FirstName
    $LastName = $item.LastName
    $Email = $item.Email
    $displayName = "$FirstName $LastName"
    $UserName = "$FirstName $LastName"
    if ((Get-ADObject -LDAPFilter "(mail=*$Email)") -or (Get-ADObject -LDAPFilter "(displayName=*$displayName)"))
    {
        if (($null -eq $Email) -or ('' -eq $Email))
        {
            Write-Warning "$i contact for $displayName has no email at all.  So we won't create a contact for him."
        }
        else
        {
            Write-Warning "$i contact for $displayName ($Email) already exists"
        }
    }
    else
    {
        "$i contact for $displayName  ($Email) doesn't exist, will create"
        $sAMAccountName = "$FirstName.$LastName"
        $localProxyEmail = "$sAMAccountName@$UserDomain"
        if ($item.Language -eq "Français"){"language is French for $displayName"; $language="fr-BE"}
        elseif ($item.Language -eq "Néerlandais"){"language is Netherlands for $displayName"; $language="nl-NL"}
        Else {"no language ($($item.Language) for $displayName, default to Netherlands"; $language = "nl-NL"}
        $proxyAddresses = @("SMTP:$Email","smtp:$localProxyEmail") # this first array will be included in the "other attributes" array below
        $OtherAttributes = @{
            'displayName'=$displayName
            'mail'=$item.Email
            'proxyAddresses'=$proxyAddresses
            'givenName'=$item.FirstName
            'sn'=$item.LastName
            'c'='BE'
            'Title'=$item.JobTitle
            'company' = "Your Company"
            'language' = $language}
        $NewContactParams = @{
            'Type' = "Contact"
            'Name' = $UserName
            'OtherAttributes' = $OtherAttributes
            'Path' = "$OU"}
        New-ADObject @NewContactParams
    }
 }

contacts, list

Get-ADObject -filter {objectclass -eq "contact"}

contacts, list all for an OU - see OU, list all contacts for an OU

contact, set property of - unlike users, many properties don't already exist. Instead, you must explicitly add them. For example, you can't simply set a language to a user who doesn't already have one specified:

Get-ADObject -LDAPFilter "(displayName=Benoît Smith)" -Properties name, language | Set-ADObject -language "fr-BE"

because it will fail with

Set-ADObject : A parameter cannot be found that matches parameter name 'language'.

even though it looks like there's an empty slot for it all ready to be filled when you look at it in something like ADUC. Instead of trying to modify a property you think ought to already exist, explicitly add it instead. It will probably work better:

Get-ADObject -LDAPFilter "(displayName= Benoît Smith)" -Properties name, language | Set-ADObject -Add @{language='fr-BE'}

country code, update

assume you want to update the country code for all users in any OU that contains the string "UK" to "GB" (only if it's not already "GB")

Get-ADUser -filter * -Properties name, givenName, middleName, sn, mail, co, c, country  | `
    where-object {($_.distinguishedname -like "*UK*") -and ($_.c -ne "GB")} | % {Set-ADUser -Identity $_ -replace @{c="GB"}}

verify

Get-ADUser -filter * -Properties name, givenName, middleName, sn, mail, co, c, country | `
    where-object {$_.distinguishedname -like "*UK*"} | Sort-Object co, sn, givenName | select name, co, c, country, givenName, middleName, sn, mail | ft

create user - see user, create

–D–

distribution group, find

find by name

Get-ADGroup -Filter {(GroupCategory -eq "Distribution") -and (Name -like "Accounting*")} -Properties name, mail, distinguishedName | ft name, mail, distinguishedName

or, to find distribution group corresponding to a certain email

Get-ADGroup -Filter {(GroupCategory -eq "Distribution") -and (mail -like "Accounting*")} -Properties name, mail, distinguishedName | ft name, mail, distinguishedName

does a user exist - see user exists or not?

domain controller, nearest

(Get-ADDomainController -Discover).Hostname

domain controller, replicate

Repadmin /replicate $Destination $Source 'dc=yourDomain,dc=com'

or

Repadmin /replicate "DC1" "DC2" 'dc=yourDomain,dc=com'

–E–

email, find AD Object using - see

employeeType, add

find users whose title does not contain the word "contractor" and make their employeeType = "employee"

Get-ADUser -SearchBase "OU=yourOU,DC=yourDomain,DC=com" `
    -Filter '(title -ne "*") -and (title -notlike "*contractor*")' -SearchScope OneLevel | `
    Set-ADUser -Add @{employeeType='employee'}

contacts in an OU

Get-ADObject -filter {objectclass -eq "contact"} `
    -SearchBase "OU=yourOU,DC=yourDomain,DC=com" `
    -SearchScope OneLevel | `
    Set-ADObject -Add @{employeeType='employee'}

exist, does a user exist - see user exists or not?

–F–

find where some entity might reside whether user/group/contact/alias - when I want to search exhaustively through AD, I run the following 5 commands in PowerShell:

$SearchUser = "someone";
Get-ADObject -LDAPFilter "objectClass=Contact" -Properties Name,mail | Where-Object{$_.mail -like "$($SearchUser)*"} | ft Name, mail, distinguishedName;
Get-ADGroup -Filter {(GroupCategory -eq "Distribution") -and (mail -like "$($SearchUser)*")} -Properties name, mail, distinguishedName | ft name, mail, distinguishedName;
Get-ADGroup -Filter {(GroupCategory -eq "Security") -and (mail -like "$($SearchUser)*")} -Properties name, mail, distinguishedName | Sort-Object mail | ft name, mail, distinguishedName;
Get-ADUser -Filter {mail -like "$($SearchUser)*"} -Properties UserPrincipalName, mail, distinguishedName | ft UserPrincipalName, mail, distinguishedName;
Get-ADUser -filter * | where-Object {$_.ProxyAddresses -match "$($SearchUser)" } | fl;

To look for:

Respectively

–G–

Get-ADUser, all properties - see user, all properties

Get-ADUser, filter on a property to be null - see null, filter on property

groups, find to which groups a user belongs

Get-ADPrincipalGroupMembership someUser | select Name, GroupCategory, GroupScope

groups, delete a user from all but one

We don’t want to remove this user from “Domain Users” just yet – especially if we’re going to keep his ID around for a while as a shared mailbox accessible by his successor.

There's no provider filter parameter for Get-ADPrincipalGroupMemebership, so we must use late filtering:

Get-ADPrincipalGroupMembership someUser | Where-Object {$_.name -ne 'Domain Users'} | select name, GroupCategory, GroupScope

Remove users from all groups in AD.  Go to their ID in ADUC and look what’s in “member of”.  To remove his membership in all groups except “Domain Users”.  Or, with PowerShell

Get-ADPrincipalGroupMembership someUser | Where-Object {$_.name -ne 'Domain Users'} | % {Remove-ADPrincipalGroupMembership -Identity someUser -MemberOf $_ -confirm:$false}

groups in an OU, display

Get-ADGroup -Filter '*' | select-object * | where -object {$_.distinguishedname -like "*,OU=yourOU,*"} | sort-Object groupCategory,GroupScope,name | ft name,groupCategory,GroupScope, DistinguishedName

or

Get-ADGroup -Filter * -SearchBase 'OU=yourOU,DC=yourdomain,DC=com' | sort-Object SearchBase,groupCategory,GroupScope,name | ft name,groupCategory,GroupScope, DistinguishedName

groups, list by type

Get-ADGroup -filter * | Sort-Object GroupCategory,GroupScope,Name | ft Name,GroupCategory,GroupScope, DistinguishedName

–H–

–I–

–J–

–K–

–L–

–M–

–N–

name wildcard - see sAMAccountName, find all objects containing a substring of a sAMAccountName (for users, contacts, groups, etc.)

nearest domain controller - see domain controller, nearest

new user - see user, create

null, filter on property

In this example, we want to find all ADUsers whose msExchHideFromAddressLists property is not set. So we quite reasonably attempt to filter on that filter not equal to the $null variable:

Get-ADuser -filter {msExchHideFromAddressLists -eq $null} -Properties msExchHideFromAddressLists | ft Name, msExchHideFromAddressLists

But that fails with:

Get-ADuser : Variable: 'null' found in expression: $null is not defined.

So, instead filter on -notlike "*":

Get-ADuser -filter {msExchHideFromAddressLists -notlike "*"} -properties msExchHideFromAddressLists | ft Name, msExchHideFromAddressLists

You can actually still filter on the $null variable. Just not in the very first part of the command where you're using the -filter. Instead, use later after a pipe:

Get-ADuser -filter * -properties msExchHideFromAddressLists | ? {$_.msExchHideFromAddressLists -eq $null} | ft Name, msExchHideFromAddressLists

I like to think that the first method of filtering on -notlike "*" is more efficient and elegant.

–O–

OU, list all contacts for an OU

Get-ADObject -filter {objectclass -eq "contact"} -Properties name, givenName, middleName, sn, mail | `
    where-object {$_.distinguishedname -like "*yourOU*"} | Sort-Object sn, givenName | select name, givenName, middleName, sn, mail | ft

Maybe more efficient to limit up front using the -SearchBase parameter below rather than after the fact using the where-object parameter like what we do above:

Get-ADObject -filter {objectclass -eq "contact"} -SearchBase "OU=yourOu,DC=yourDomain,DC=com" -Properties name, givenName, middleName, sn, mail | `
    Sort-Object sn, givenName | select name, givenName, middleName, sn, mail | ft

And perhaps also sort first by email domain

Get-ADObject -filter {objectclass -eq "contact"} -Properties name, givenName, middleName, sn, mail | `
    where-object {$_.distinguishedname -like "*yourOU*"} | `
    Select-Object @{n="Dom";e={$_.mail.split("@")[1]}}, name, givenName, middleName, sn, mail | `
    Sort-Object Dom, sn, givenName | ft

list emails

Get-ADObject -SearchBase 'OU=MyOu,DC=myDomain,DC=com' -Filter {objectclass -eq "contact" } -Properties mail | Select-Object Name, mail

OU, list all users for an OU

this level and all levels below that, specify -SearchScope Subtree (or just leave that parameter out and it will search all levels below by default)

Get-ADUser -SearchBase "OU=yourOU,DC=yourDomain,DC=com" -Filter * -SearchScope Subtree | ft

to just list the highest level, specify -SearchScope OneLevel

Get-ADUser -SearchBase "OU=yourOU,DC=yourDomain,DC=com" -Filter * -SearchScope OneLevel | ft

OUs (Organizational Units), list

Get-ADOrganizationalUnit -filter * | ft Mame, DistinguishedName

to just list the OUs one level down in a specific OU, specify -SearchScope OneLevel

Get-ADOrganizationalUnit -Searchbase "OU=yourOU,DC=yourDomain,DC=com" -SearchScope OneLevel -Filter * | ft

OUs for contacts (just the lowest level)

Get-ADObject -filter {objectclass -eq "contact" } -Properties targetaddress,distinguishedName | Sort-Object {((($_.DistinguishedName.Split(',', 2))[1]).Split(',', 2))[0]},name | select name, targetaddress,@{Name='OU';Expression={((($_.DistinguishedName.Split(',', 2))[1]).Split(',', 2))[0]}} | ogv

–P–

permissions, list for a user

(Get-ACL "AD:$((Get-ADUser someUser).distinguishedname)").access | select objectType, IdentityReference, inheritedObjectType, ActiveDirectoryRights

haven't found this to be too useful

properties, see all - sometimes by default, when you do a get "-" even with a "fl" appended, you don't get all the properties

Get-ADUser somauser -Properties *

property - is a property missing for a user?

You might think this might work

if (($contact.$property -eq $null) -or ($contact.$property -eq ''))

But it doesn't. Use this instead.

if (-not($contact.$property))

–Q–

–R–

rename a user

Seems like this ought to be simple, right? But problem: it seems that you need to use the Rename-ADObject and that command wants an identity. And all you might have is a name. So you have to pipe the Get-ADuser into a Set-ADuser (in order to get an object with an identity) and then finally pipe that into Rename-ADObject. The first two commands are probably superfluous; included here in case you already had $DepartingUserIdentity as a variable earlier in a script. The last command is what you really need.

$DepartingUserIdentity = "someUser";
$DepartingUserName = (Get-ADUser $DepartingUserIdentity).Name
Get-ADUser $DepartingUserIdentity | Set-ADUser -PassThru | Rename-ADObject -NewName "departed $DepartingUserName" -PassThru

make sure display name matches

Change the display name.  Otherwise, will retain the old name when looking at shared mailboxes in Exchange Online

Get-ADUser $DepartingUserIdentity -Properties DisplayName | select name, DisplayName

It's kind of weird having to invoke "Foreach-Object" (%) for just one user.  But doesn't work with merely "| Set-ADUser -DisplayName $_.name" - puts in a null

Get-ADUser $DepartingUserIdentity -Properties DisplayName | Set-ADUser -DisplayName $_.name

so invoke "Foreach-Object" (%)  - even if we're doing this for just one user

Get-ADUser $DepartingUserIdentity -Properties DisplayName | % {Set-ADUser -Identity $_ -DisplayName $_.name}

replicate domain controller - see domain controller, replicate

–S–

sAMAccountName, find all objects containing a substring of a sAMAccountName (for users, contacts, groups, etc.)

Get-ADObject -Filter "SamAccountName -like '*marketing*'" -Properties DisplayName, sAMAccountName, mail | Select-Object DisplayName, Name, sAMAccountName, mail, objectClass | ft

sAMAccountName wildcard - see sAMAccountName, find all objects containing a substring of a sAMAccountName (for users, contacts, groups, etc.)

search for where some entity might reside whether user/group/contact/alias - see find where some entity might reside whether user/group/contact

security group, find email-enabled

Get-ADGroup -Filter {(GroupCategory -eq "Security") -and (mail -like "*")} -Properties name, mail, distinguishedName | Sort-Object mail | ft name, mail, distinguishedName

SID, find name for

$objSID = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-898656534-286731432-926709055-10765");
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount]);
$objUser.Value

sync domain controllers, see domain controller, replicate

–T–

title, find users who don't have one like

so invoke "Foreach-Object" (%)  - even if we're doing this for just one user

Get-ADUser -SearchBase "OU=yourOU,DC=yourDomain,DC=com" -Filter '(title -ne "*") -and (title -notlike "contractor")' -SearchScope OneLevel | ft

title, change all contacts in an OU (that has nothing but contacts)

Get-ADObject -filter {objectclass -eq "contact"} -SearchBase "OU=yourOU,DC=yourDomain,DC=com" `
    -Properties name, givenName, middleName, sn, mail, employeeType, title | `
    Set-ADObject -Add @{title='inspector'}

trust relationship broken

Test-ComputerSecureChannel -credential yourdomain\someadmin -Repair

–U–

user, all properties

if you try to get a "full list" of all the properties for a user, you'll end up with a rather disappointingly small list:

Get-ADUser someuser

You know there's more stuff buried in there! So use this instead:

Get-ADUser someuser -Properties *

user, compare all properties for a list

("user1", "user2") | %{Get-ADUser $_ -Properties *} | export-csv "c:SomeFile.csv"

user, create

$UserName = "$FirstName $LastName"
$sAMAccountName = "$FirstName.$LastName"
$DefaultPassword = "topSecret"
$UPN = "$sAMAccountName@$UserDomain"
$NewUserParams = @{
    'UserPrincipalName' = $UPN
    'Name' = $UserName
    'DisplayName' = $UserName
    'GivenName' = $FirstName
    'Surname' = $LastName
    'Title' = $Title
    'Department' = $Department
    'SamAccountName' = $sAMAccountName
    'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force)
    'Enabled' = $true
    'Initials' = $MiddleInitial
    'Path' = "$OU"
    'ChangePasswordAtLogon' = $false
    'EmailAddress' = $UPN
}
New-ADUser @NewUserParams

user exists or not?

$User = Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue
If ($Null -ne $User) {"$upn exists in Azure AD"}

Else {"$upn not found in Azure AD"}

user, find by wildcard (and other objects as well) - see sAMAccountName, find all objects containing a substring of a sAMAccountName (for users, contacts, groups, etc.)

users, list

Get-ADUser -Filter * | ft

users, list all for an OU - see OU, list all users for an OU

userParameters, find users whose userParameters is not null

Get-ADUser -Filter * -Properties samAccountName, userParameters | where {$_.userParameters -ne $null} | Sort-Object samAccountName | fl samAccountName, userParameters

–V–

–W–

wildcard for users, contacts, groups, etc. - see sAMAccountName, find all objects containing a substring of a sAMAccountName

–X–

–Y–

–Z–