Powershell Get-Aduser

Trying to write a script that will check whether a few accounts are enabled, locked out, and return the last password reset time.  Any reason why $User.LockedOut or $_.LockedOut will not return a value?
$Users = "USER1",
"USER2",
"USER3"
ForEach ($User in $Users) {
Get-ADUser $User -Properties Name,sAMAccountType,Enabled,LockedOut,PasswordLastSet | Select Name,sAMAccountName,Enabled,LockedOut,PasswordLastSet | Out-Null
# Check if account is Enabled or Disabled
Write-Host $User.LockedOut

$User is just a string, in the code you've posted. You're calling Get-ADUser, but not saving the object that it returns anywhere (and in fact, you're piping it to Out-Null.)
Try this:
$Users = "USER1",
"USER2",
"USER3"
ForEach ($UserName in $Users) {
$User = Get-ADUser $UserName -Properties Name,sAMAccountType,Enabled,LockedOut,PasswordLastSet
# Check if account is Enabled or Disabled
Write-Host $User.LockedOut

Similar Messages

  • How to add SaveFileDialog to PowerShell Get-ADUser Export-CSV

    Hi,
    I am having a bit of difficulties with getting the SaveFileDialog to work when I use the Get-ADUser export-CSV.
    Current code:
    $handler_Output_Click=
    $User = Get-Aduser $textBox1.Text -Properties DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Select DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Export-CSV C:\temp\test.csv -NoTypeInformation ';' -encoding utf8
    $richTextBox1.Text = "A file 'test.csv' has been created to C:\temp\ based on the user: $($textBox1.Text)"
    Here a specific filename is already defined and I have to edit the code each time I want a different filename.
    It would be perfect if I could implement the SaveFileDialog box so I have the ability to name the file before saving and possibly even have the option to select the file type (among .CSV and All files).
    This it the export/output button itself:
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 502
    $System_Drawing_Point.Y = 38
    $Output.Location = $System_Drawing_Point
    $Output.Name = "Output"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 85
    $Output.Size = $System_Drawing_Size
    $Output.TabIndex = 2
    $Output.Text = "Export as file"
    $Output.UseVisualStyleBackColor = $True
    $Output.add_Click($handler_Output_Click)
    # $form1.AcceptButton = $Output
    $Output.DataBindings.DefaultDataSourceUpdateMode = 0
    $form1.Controls.Add($Output)
    And in the beginning of my script I also have defined the following:
    [System.Windows.Forms.Application]::EnableVisualStyles();
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms.SaveFileDialog") | Out-Null
    And also:
    $Output = New-Object System.Windows.Forms.Button
    Any ideas how can I implement the SaveFileDialog so when I press the "Export as file" button the PowerShell command "Get-Aduser $textBox1.Text -Properties DisplayName,sAMAc..." is ran and I can choose the file name from a pop-up
    dialog box where to save the file and also put a filename? Currently I have to edit the code in order to assign a new file name (or go rename the file from that location).
    Thank you in advance,
    Henri
    EDIT:
    I know that the below is the answer to the SaveFileDialog, however I cannot imagine how I could implement it to my script into the "Get-Aduser $textBox1.Text -Properties a,b,c,d | select a,b,c,d | Export-CSV C:\temp\test.csv" cmdlet.
    Function Get-SaveFile($initialDirectory)
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
    Out-Null
    $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
    $SaveFileDialog.initialDirectory = $initialDirectory
    $SaveFileDialog.filter = "All files (*.*)| *.*"
    $SaveFileDialog.ShowDialog() | Out-Null
    $SaveFileDialog.filename

    Just run the dialog before exporting the file.  Why is that a problem?
    \_(ツ)_/
    It works now! I made some modifications and it works. Thank you very much for the advice.
    $handler_Output_Click={
    Add-Type -AssemblyName System.Windows.Forms
    $SaveAs1 = New-Object System.Windows.Forms.SaveFileDialog
    $SaveAs1.Filter = "CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt|Excel Worksheet (*.xls)|*.xls|All Files (*.*)|*.*"
    $SaveAs1.SupportMultiDottedExtensions = $true;
    $SaveAs1.InitialDirectory = "C:\temp\"
    if($SaveAs1.ShowDialog() -eq 'Ok'){
    $User = Get-Aduser $textBox1.Text -Properties DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Select DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Export-CSV $($SaveAs1.filename) -NoTypeInformation ';' -Encoding UTF8
    $richTextBox1.Text = "A file $($SaveAs1.filename) has been created based on the user: $($textBox1.Text)"

  • Powershell Get-ADUser returns Computer objects as well ???! How to prevent.

    I ran the following script and got a bunch of computer objects in my csv. How to i Prevent this? I already tried using 
    Where-Object{$_.type
    -eq
    "user"} OR
     -filter{type
    -eq
    "user"}
    script:
    Get-ADUser-Filter*-PropertiessamAccountName,accountExpires,Created,LastLogonTimeStamp,Department,physicalDeliveryOfficeName,employeeID,AccountExpirationDate,Manager|
    Where-Object
    {$_.accountexpirationdate
    -lt$timex}
    |
    select
    Name,samAccountName,@{Name="Timestamp";
    Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}},@{n='Date
    Created';e={$_.created}},Department,@{n='Location';e={$_.physicalDeliveryOfficeName}},employeeID,AccountExpirationDate,@{Label='Manager
    sAMAccountName';Expression={(Get-ADUser$_.Manager).sAMAccountName}},@{Label='Manager
    Name';Expression={(Get-ADUser$_.Manager).name}}
    |
    export-csv
    -path$mypath-notypeinformation

    Someone told me the Computer accounts are generic accounts...makes any sense?
    No.
    EDIT: What's the output of this command for one of these computer accounts:
    Get-ADUser ThatComputerAccount | Select *
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • Powershell get-aduser filter problem

    Powershell'Filter' = {(Enabled -eq $True) -and ((Office -ne "EXCLUDE") -or (Office -notlike '*'))}
    The filter parameter isn't very user friendly.  Try this and see if it is what you want.

    Hello all, I am trying to filter a script I found here from Martin9700to get users from an ad ou. The original line: 'Filter' = {Enabled -eq $True} works and I am trying to add a filter to exclude users that have Office value of EXCLUDE. If I use: 'Filter' = {(Enabled -eq $True) -and (office -eq "EXCLUDE")} then it will get the user that has EXCLUDE but I can't get any negative to work. I have tried -ne, -notlike and several combos of syntax but I really don't understand much of it. Any help would be greatly appreciated! The complete script is below. Thanks!

  • Powershell get-ADUser Security

    Hello
    I've got a question, is it possible to get the Securitycontext of an Useraccount (which groups/Users has access to the account and with wihich rights? --> img)
    Thank you in advance.
    n0rthclub
    n0rthclub

    Hi,
    Just checking in to see if the suggestions were helpful. Please let us know if you would like further assistance.
    TechNet Subscriber Support
    If you are
    TechNet Subscription
    user and have any feedback on our support quality, please send your feedback
    here.
    Regards, Yan Li

  • The Command Get-ADUser -Identity username -Properties * No Longer Works Due to a Bug in PowerShell 4 and Win8-1 Pro

    The 'Command Get-ADUser -Identity <username> -Properties *' No Longer Works Due to a Bug in PowerShell 4 and Win8-1 Pro
    It produces the following error:
    Get-ADUser : One or more properties are invalid.
    Parameter name: msDS-AssignedAuthNPolicy
    At line:1 char:1
    + Get-ADUser -Identity ********** -Properties *
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (**********:ADUser) [Get-ADUser], ArgumentException
        + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
    This is already documented in these forums:
    1. http://social.technet.microsoft.com/Forums/systemcenter/en-US/1bf9568e-6adc-495d-a37c-48877f86985a/powershell-40-and-the-activedirectory-ps-module?forum=w81previtpro
    2. https://connect.microsoft.com/PowerShell/feedback/details/806452/windows-8-1-powershell-4-0-get-adcomputer-properties-bug
    Unfortunately, in typical style, Microsoft have archived number 1 without bothering to respond with advice.  Can someone in Microsoft please advise your customers here if this is being investigated and of any available workaround or fix ?
    -- huddie "If you're not seeking help or offering it, you probably shouldn't be here."

    Did you consider using one of the "workarounds" below to run an existing version of the AD Module for PowerShell under a specific PowerShell version:
    a. #require -version 3.0    (in ps1 script)
    b. powershell -version 3.0
    Thank you for sharing with us if this helps.
    Desmond, did you miss my reply below ?  I still haven't heard back from you:
    >> "Desmond,
    >> 
    >> Thanks for your quick response.
    >> 
    >> I'm running this just as a command, not in a script:
    >> 
    >> Get-ADUser -Identity <username> -Properties *
    >> 
    >> When I try to run powershell
    -version 3.0 first, then run the above command, it still fails with the same error.  When I then run Get-Host,
    the version still shows as 4.0 so maybe there's more I need to do to launch a 3.0 host.  Anyway, from what I've read it seems your command is more aimed at script compatibility.
    >> 
    >> Can you help ?"
    -- huddie "If you're not seeking help or offering it, you probably shouldn't be here."

  • Get-aduser - Export-CSV -- POWERSHELL

    I need help in getting this command to export the data into a CSV.
    Get-ADUser -Filter * -Properties
    whenCreated | Where-Object {$_.whenCreated -ge ((Get-Date).AddDays(-30)).Date} | FL SamAccountName, Name, DistinguishedName, whenCreated
    | Export-Csv
    c:\scripts\ADCreatedUsers.csv
    When doing this the command does not give me anything close to what I expect.

    Duplicate thread.
    Active thread is here:
    https://social.technet.microsoft.com/Forums/scriptcenter/en-US/15c5347a-4c18-404c-a9f9-0ba48b932384/getaduser-exportcsv-powershell?forum=ITCG
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Powershell AD Cmdlet Get-Aduser does display "homedirectory"

    Hey Scripting Guys,
    i trying to display the homedirectory path of some users. My Powershell command look's something like that:
    Get-Aduser -Identy myuser -Properties Homedirectory
    But the attribut is displayed without a value. Has somebody an idea?
    THX.

    The User has a value assigned to the homeDirectory, but it is not displayed in powershell.
    When i export my query into a text file, the homedirectory is displayed correct - leave it a that.
    Now i trying to export in a csv, without success.
    Get-Aduser - Filter * -Properties homeDirectory -Searchbase "my dn" | Where-object { $_. homeDirectory -match "my path" } | ft homeDirectory, samAccountName | Export-CSV -NoTypeInformation C:\Myfile.csv
    The File is createt, but without content. I think there is no syntax error.
    Some idea?
    This will not wwork:
     ft homeDirectory, samAccountName | Export-CSV -NoTypeInformation C:\Myfile.csv
    You cannot oputput FT to Export-CSV.  Remove the FT.  Change it to select.
    ¯\_(ツ)_/¯

  • Powershell: Why does this Get-ADUser command return Nada??!

    get-aduser-filter*-propertiesName,employeeID|Where-Object{$_.type
    -like"*user*"}

    selectName,employeeID|out-gridview

    get-aduser-filter*-propertiesName,employeeID|Where-Object{$_.type
    -like"*user*"}

    selectName,employeeID|out-gridview
    At line:1 char:34
    + get-aduser-filter*-propertiesName,employeeID|Where-Object{$_.type -like"*user*"} ...
    +                                  ~
    Missing argument in parameter list.
    At line:1 char:95
    + ... } |  selectName,employeeID|out-gridview
    +                    ~
    Missing argument in parameter list.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : MissingArgument
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • Is there a way to speed up Get-QADUser or Get-ADUser?

    Hello,  I was wondering if there was a way to speed the commands up to query faster?  My one-liner looks like:
    Get-ADUser -SearchBase "OU=People,DC=Domain,DC=Company,DC=Net" -Filter {Title -eq "Job Title"} -ResultSetSize $null -Properties * | Select SamAccountName, DisplayName, Manager
    Are we able to somehow omit property fields that it looks up?  Would that help?
    I've tried looking through Google and couple of forums, but could not find the answer.
    I have used a tool called "ADFind" and was able to get the results in less than 5 minutes, but Powershell seems to take WAYY longer to do this.
    Thank you!

    Hi,
    Yes, drop the wildcard from Properties and only request the properties that you're interested in.
    Out of curiosity, how many users are returned by this query?
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • Error troubleshooting in AD Module - Get-Aduser w/created filter

    Hi All,
    I'm working as an intern with my university, and I've been tasked with clearing out old student accounts in AD. There are currently over 4000 users in our system, and it's estimated that there are over 3500 old accounts that need to be deleted.
    We are at the 2008 R2 Domain Functional Level.
    I am going to script this through Powershell, but I'm having a terrible time getting a certain query to run properly.
    I am using the following:
    get-aduser -filter {created -lt '1/1/2010' -and lastlogontimestamp -notlike '*'} -properties created
    I will sometimes narrow my query by adding another filter for created -gt '1/1/2008', for instance.
    When I run the command as written, however, it will return several hundred users, but then it spits out the following error after the last displayed result:
    Get-ADUser : The specified method is not supported
    At C:\Users\Administrator.CSC\Desktop\test1.ps1:4 char:15
    + get-aduser <<<< -filter {created -lt '1/1/2010'} -properties created | ft name,samaccountname,created
    + CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : The specified method is not supported,Microsoft.ActiveDirectory.Management.Commands.GetADUser
    If I narrow my search scope by created date, I can sometimes get the error to not appear. My guess is that there are several accounts in the database that trigger the error (or at least, that's how it appears).
    I have tried running this on both a DC and a non-dc server with server management tools installed. It doesn't matter what other filters are used, so omitting the lastlogontimestamp filter doesn't prevent the error.
    My supervisor seems to think there may be errors in the AD database, but I've done every AD health check I can think of.
    Does anyone have any suggestions?
    Thanks,
    Brandon

    If you have access to Microsoft Connect (I believe you must be an MVP), it would help to vote on this report, as that should help prioritize it.
    You don't need to be a MVP for access to Connect, here's a direct link to the bug report Richard opened:
    https://connect.microsoft.com/PowerShell/feedbackdetail/view/963333/ad-module-cmdlets-raise-error-if-there-are-more-than-256-results
    The command from the report does appear to work for me in v4 (Win7):
    PS C:\> Get-ADUser -Properties Created -Filter "Created -gt '9/1/2014'" | measure
    Count : 260
    I also tested the command that failed in the post above and v3 appears to be working for me as well (WS2012):
    PS C:\> $start = (Get-Date).AddDays(-1)
    PS C:\> get-aduser -filter {modified -gt $start} | measure
    Count : 263
    Perhaps the count needs to be higher to replicate this.
    EDIT: I just created a bunch of new user accounts and I still can't replicate this (v3 on WS2012 again):
    PS C:\> $start = (Get-Date).AddDays(-1)
    PS C:\> get-aduser -filter {modified -gt $start} | measure
    Count : 1803
    EDIT2: DC is WS2008SP2.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Use Get-ADUser to get locked status and if locke give a choice to unlock it.

    Hi guys and girls,
    Im startling to learn powershell scripting and have made my first tool/Script.
    Below script is the one i use, however i do have an problem i would like some help with.
    I use the script to display some basic info and also to show if the user is lockedout or not.
    However i do would like to have the choice to unlock the user in the script as well, therefore im using the if statement.
    But dont get it to return the value i want. What i want it to do is to check if the account is locked if so ask if it should unlock it. Any help or input is appreciated.
    /Json
    $userinput = Read-Host "Enter Username Here"
    Get-ADUser -Identity $userinput -Properties * | Select-Object DisplayName, city, department, EmailAddress, HomeDirectory, MobilePhone, OfficePhone, Manager, PasswordExpired, PasswordLastSet, LockedOut
      If(((Get-ADUser -Identity $userinput -Properties lockedout).lockedout = $true))

    Hi there, I've not tested this properly but it should do the trick.
    add-type -AssemblyName System.DirectoryServices.AccountManagement
    $userinput = Read-Host "Enter Username Here"
    $res = Get-ADUser -Identity $userinput -Properties DisplayName, city, department, EmailAddress, HomeDirectory, MobilePhone, OfficePhone, Manager, PasswordExpired, PasswordLastSet, LockedOut | Select-Object DisplayName, city, department, EmailAddress, HomeDirectory,
    MobilePhone, OfficePhone, Manager, PasswordExpired, PasswordLastSet, LockedOut
    if ($res.lockedout -eq $true){
    $unlock = Read-host "Unlock? Y/N"
    if ($unlock -eq "Y")
    $context = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context,$userinput).UnlockAccount()

  • Using Get-ADUser but 3.0 needs a filter? What changed?

    I'm trying to just do a basic query of AD attributes from a text file of SamAccountNames I have, but I'm upgraded to PowerShell ISE 3.0 and there might be some things new I'm not understanding. 
    I was just trying to do something simple like this; Get-Content C:\Scripts\userabrivs.txt | ForEach { Get-ADUser -Properties * } | Export-csv C:\scripts\Output\adusers1 
    but in ISE it always asks for 
    cmdlet Get-ADUser at command pipeline position 1
    Supply values for the following parameters:
    (Type !? for Help.)
    Filter: 
    I'm not very good at this so can someone help me understand why it needs a filter when I'm just asking it to use the list of SamAccountNames I have in a text file?

    Hi,
    You're never telling Get-ADUser which user you want to return. Try this instead:
    Get-Content .\userList.txt | ForEach {
    Get-ADUser -Identity $_ -Properties *
    } | Export-Csv .\userProperties.csv
    I highly recommend only returning the properties you need, the wildcard will return more information than most people want to look at.
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • Get-Aduser Filtering Issue

    Hey Guys,
    I'm trying to do a get-aduser filter based on two criteria 
    1. the account is enabled
    2. the samaccountname does not contain the word health
    I'm stumped on this one. Here's what i have thus far. I have to be close
    Get-ADuser -Filter 'enabled -eq $true' -and 'SamAccountName -ne "Health*"'
    Thoughts ? This is driving me crazy.
    Rich
    Rich Thompson

    Hi,
    afaik the -Filter-parameter only applies to AD-properties. enabled is a powershell-AD-object property. It is represented by the UserAccountControl flag in the ActiveDirectory (see description
    here) and you'l combine it with the SAMAccountName, similiar to something like this:
    Get-ADUser -filter {((userAccountControl -like "512") -and (samaccountname -notlike "Health*"))}
    Regards
    Sebastian
    You can filter on the Enabled property with no issues. Also, just FYI, -Filter wants a string, not a scriptblock. Scriptblocks will generally work, but not always.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Powershell - get details about members of ad group

    hi, i want to perform this task:
    Get a list with name, samaccountname and department for all members of an ad-group. I have been trying with different ways, but still no complete success. Need def more powershell skills. Anybody who can guide me in the right direction here? Thanks
    in advance.

    Here's an alternative method which can be used as a workaround if you run into issues with large groups (5000+ users).
    (Get-ADGroup "groupname" -properties members).members | Get-ADUser -properties Department |
    Select-Object SamAccountName, Name, Enabled, Department | Export-CSV ".\USERS005.csv" -noType
    Enabled is a default property for Get-ADUser so you don't need to specifically include this in the properties.  (Department is not, so you do need to include this).
    Due to performance reasons, commands do not return all the properties of a object.
    For example.  Get-ADUser returns the following properties by default.
    DistinguishedName
    Enabled
    GivenName
    Name
    ObjectClass
    ObjectGUID
    SamAccountName
    SID
    Surname
    UserPrincipalName
    If you want to know the default properties for a given command, you can expand the propertynames.
    For example :-
    Get-ADUser 'user' | select -expand propertynames
    or
    (Get-ADUser 'User').propertynames

Maybe you are looking for

  • After Patch  10.2.0.4, got "voting disk  corrupted" error.

    Dear all, My setting is: OS:RHEL4.8 U8 x86 DB:10.2.0.1 CRS:10.2.0.1 After I installed Patchset 10.2.0.4 and execute $CRS_HOME/install/root102.sh, I could't start clusterware anymore. After checking ocssd.log, I found some messages like this: [    CSS

  • Problem in my leptop

    It is a V6211 au model. When the A/C adapter is plugged in, the ring around the plug jack is lit and the icon for charging the battery is lit also. When I press the power button to start up the laptop, the rest of the icons light up in blue and the f

  • 8.1.7 management server can't start

    I tried to delete a DB service with oradim (W2K SP4, Oracle 8.1.7.0.0). Since then the management server can not start, with Windows error message Error 1075: The dependency service does not exist or has been marked for deletion. In services/properti

  • Wie CAs beseitigen in PSE 7 ?

    Hallo zusammen, habe dafür noch keine Funktion gefunden - wer kann mir helfen? Danke und Grüße UH

  • How can I access advanced settings during initial email account setup?

    Having just bought an iPad Air, I've tried to setup my email account (with John Lewis) on it during the initial startup process and repeatedly failed, both with SSL on and off. I imagine that I need to change the port settings or some other advanced