Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Write errors if creds or computer is not available

$
0
0

Howdy

I am working on another script to report on accounts and I have been able to get it working OK so far, but I would like to put in something to write to the file if the connection to the system it queries fails or if the credentials fail.

This script is below and right now I am just running it and piping the output to export-csv. 

Param

(

[Parameter(Position=0,Mandatory=$false)]

[ValidateNotNullorEmpty()]

[Alias('cn')][String[]]$ComputerName=$Env:COMPUTERNAME,

[Parameter(Position=1,Mandatory=$false)]

[Alias('un')][String[]]$AccountName,

[Parameter(Position=2,Mandatory=$false)]

[Alias('cred')][System.Management.Automation.PsCredential]$Credential

)

$Obj = @()

$now = Get-Date

Foreach($Computer in $ComputerName)

{

If($Credential)

{

$AllLocalAccounts = Get-WmiObject -Class Win32_UserAccount -Namespace "root\cimv2" `

-Filter "LocalAccount='$True'" -ComputerName $Computer -Credential $Credential -ErrorAction Stop

}

else

{

$AllLocalAccounts = Get-WmiObject -Class Win32_UserAccount -Namespace "root\cimv2" `

-Filter "LocalAccount='$True'" -ComputerName $Computer -ErrorAction Stop

}

$Obj = $AllLocalAccounts | ForEach-Object {

         $user = ([adsi]"WinNT://$computer/$($_.Name),user")

         $pwAge    = $user.PasswordAge.Value

         $maxPwAge = $user.MaxPasswordAge.Value

         $pwLastSet = $now.AddSeconds(-$pwAge)

            $LastLogin = $(([ADSI]"WinNT://$($computer)/$($_.name)").lastlogin)

         New-Object -TypeName PSObject -Property @{

           'Name'                 = $_.Name

           'Full Name'            = $_.FullName

            'Disabled'             = $_.Disabled

            'Description'          = $_.Description

           'Status'               = $_.Status

           'LockOut'              = $_.LockOut

           'Password Expires'     = $_.PasswordExpires

           'Password Last Set'    = $pwLastSet

           'Password Expiry Date' = $now.AddSeconds($maxPwAge - $pwAge)

           'Password Required'    = $_.PasswordRequired

           'Account Type'         = $_.AccountType

           'Domain'               = $_.Domain

 

   'Password Age' = ($now - $pwLastSet).Days

        'Last Login' = $LastLogin 

         }

       }

If($AccountName)

{

Foreach($Account in $AccountName)

{

$Obj|Where-Object{$_.Name -like "$Account"}

}

}

else

{

$Obj

}

}


Viewing all articles
Browse latest Browse all 6937

Trending Articles