Thursday 4 June 2015

Get local system users and details with PowerShell

Get local system users and details with PowerShell


Ok, now we are dealing with only the local users on the system.

a simpler way to get the details are by using the below one-liner.

Get-WmiObject -Class Win32_UserAccount -filter "LocalAccount = '$True'" -ComputerName localhost -Namespace "root\cimv2"

you could pipe the above one-liner to '| select *' at the end to get more details on the each account available.

Get-WmiObject -Class Win32_UserAccount -filter "LocalAccount = '$True'" -ComputerName localhost -Namespace "root\cimv2"  | select *



Give a try to execute this to grab remote machine users and see how it worked or didn't work...


As always.

-Happy Scripting.

How can the $? be used in powershell.

How can the $? be used in powershell.


It reports whether or not the last-run command considered itself to have completed successfully. You get no details on what happened with it. It returns a boolean value.

The $? variable is a Boolean value that is automatically set after each PowerShell statement or pipeline finishes execution.  It should be set to True if the previous command was successful, and False if there was an error.  If the previous command was a call to a native exe, $? will be set to True if the $LASTEXITCODE variable equals zero, and False otherwise.  When the previous command was a PowerShell statement, $? will be set to False if any errors occurred (even if ErrorAction was set to SilentlyContinue or Ignore.)

Just be aware that the value of this variable is reset after every statement.  You must check its value immediately after the command you’re interested in, or it will be overwritten (probably to True).



The $? variable doesn’t give you any details about what error occurred; it’s simply a flag that something went wrong.  In the case of calling executable programs, you need to be sure that they return an exit code of 0 to indicate success and non-zero to indicate an error before you can rely on the contents of $?.


Example:

Add-Computer -DomainName $Domain  -Credential $cred -OUPath $OUPath
if ($? -ne 'True') {exit 100} #if the above line of command failed for some reason it returns 'False' or if it successfully completed it returns 'True'.

Simpler example.






Happy scripting..