Search code examples
powershelluser-accounts

How to "read" a user account with Powershell


I am trying to create a backup powershell script for user documents. I have created a script where I am putting on a form box the username I want to backup and then the script proceeds. The last thing is that I want to have a rule that if I put a wrong name, the script will not proceed.

Does anyone knows how I can "read" the present useraccounts on a laptop, in order to create rule to cross-check the input with the useraccounts?

Best regards.


Solution

  • This will read all of the folders in C:\Users and attempt to find a corresponding account in AD:

    Get-Childitem C:\users -Directory |
        ForEach-Object {
            $profilePath = $_.FullName
    
            Get-AdUser -Filter {SamAccountName -eq $_.Name} |
                ForEach-Object {
                    New-Object -TypeName PsCustomObject |
                        Add-Member -MemberType NoteProperty -Name Name -Value $_.Name -PassThru |
                        Add-Member -MemberType NoteProperty -Name ProfilePath -Value $profilePath -PassThru |
                        Add-Member -MemberType NoteProperty -Name SID -Value $_.SID -PassThru
            }
    
        } | Format-Table Name,SID, profilePath -AutoSize
    

    Obviously you can modify to get different AD properties, if needed. Also, remove the Format-Table command in order to pipe the output objects for further manipulation.

    Note:

    • This requires the AD PowerShell Module to be installed on the system you run the script on.
    • It only outputs an object if it finds a user account, so you won't see anything for folders it finds that have no account.