Solved

In powershell : how should i deal with try and catch in the following situation ?

Posted on 2014-12-05
9
319 Views
Last Modified: 2014-12-09
Hello experts,

i've created a file with some names of host i have in lan.
i'm writing a script in order to know who's connected to thoses hosts.

When an user is logged in the machine the output is allright. My problem is the dislpay on the console when nobody is on the machine ,  i'd like to avoid the red informations output by powershell.


here 's my script so far, there's smtgh i'm missing on catch,
thank you in advance for help.


--------------------   script   ------------------------------------
$computers = Get-Content M:/PS_scripts/machinesTest.otl

$computers  | ForEach-Object {
   
    try {
        Get-WmiObject  win32_computersystem -ComputerName $_ | select Username,Caption,Manufacturer
    }
    catch [System.Runtime.InteropServices.COMException]
    {
        if($_.Exception.ErrorCode -eq 0x800706BA)
        {
            Write-Error  "Nobody on host : " + $_
        }
    }

}
--------------------------   Error for a machine that is problably on stand by ------------
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At M:\PS_scripts_servers\users_logged_into_test_machines.ps1:10 char:9
+         Get-WmiObject  win32_computersystem -ComputerName $_ | select Username,C ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
0
Comment
Question by:toshi_
  • 5
  • 4
9 Comments
 
LVL 40

Expert Comment

by:Subsun
ID: 40482733
Try Catch work with terminating errors. The Catch block is only accessed if a terminating error occurs, otherwise it is ignored. Try adding error action Stop
Get-WmiObject  win32_computersystem -ComputerName $_ -ea STOP | select Username,Caption,Manufacturer 

Open in new window

0
 

Author Comment

by:toshi_
ID: 40482766
hello Subsun,
thank for the replay ...

how could i inform to the console that the host has no user working on it ?
i need to have the full list of computers as response.

Thank you for further help.

toshi
0
 

Author Comment

by:toshi_
ID: 40482778
i' ve read about this -ErrorAction that change the nonterminal in a terminal error.

so how do i catch now ?
this has eliminated the red display but i'd like to catch in order to display on terminal info about ....

toshi
0
 
LVL 40

Expert Comment

by:Subsun
ID: 40482851
The error means the command unable to connect to computer, it does not mean there is no user on the computer..

Try the following code and see if you get expected result.. You can also export the result to csv file using Export-Csv
Get-Content M:/PS_scripts/machinesTest.otl | %{
$computer = $_ 
 try {
 $Users = Get-WmiObject  win32_computersystem -ComputerName $computer -ErrorAction Stop | select Username,Caption,Manufacturer
	 If (($Users | %{$_.Username}) -eq $null){
	  New-Object PSObject -Property @{
		Server = $computer
		Users = "None"
		Manufacturer = $Users.Manufacturer
		}
	 }Else{
	  New-Object PSObject -Property @{
		Server = $computer
		Users = ($Users | %{$_.Username}) -join ","
		Manufacturer = $Users.Manufacturer
		}
	 }
 }
 catch
 {
	  New-Object PSObject -Property @{
		Server = $computer
		Users = $_.Exception
		Manufacturer = "NA"
	}
 }
}

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:toshi_
ID: 40482984
hello Subsun,
sorry for the delay.....

here are  the kind of errors that i'm  receiving,
i'm not able to work out what is going bad
when debugging this error come up on line $Users = .....
before the IF.

could you help me understand ?
thanks in advance


Server                                             Users                                              Manufacturer                                      
------                                             -----                                              ------------                                      
machinename                                       System.Runtime.InteropServices.COMException (0x... NA                                                
The PowerShell instance is not in the correct state for creating a nested PowerShell instance. Nested PowerShell instances should only be created in a
running PowerShell instance.
At M:\PS_scripts_servers\users_logged_into_test_machines2.ps1:27 char:1
+ $computer = $_
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidOperation
0
 

Author Comment

by:toshi_
ID: 40482988
the first machine is the one i'm working on, so there should be an answer at least for this machine ?
am I wrong ?

toshi
0
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
ID: 40483119
In my code change line 23 from Users = $_.Exception to Users = $_.exception.message

This will give you the exact error message..

Mostly the error will be related to RPC.. Basically the command not able to access the WMI information from remote server. There are many reason for this error.. Probably RPC service not running in remote computer or port are blocked etc.. You can search in Google to find related Microsoft articles for troubleshooting.
0
 
LVL 40

Expert Comment

by:Subsun
ID: 40483133
BTB if you are trying to find the RDP sessions then this wont work. This command will not list the RDP sessions.

If RDP, you can try this code which is from TechNet scripting gallery
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-script-to-Find-d2ba4252
0
 

Author Comment

by:toshi_
ID: 40488864
thanky a lot subsun,
i have exactly what i wanted : names that are logged on hosts ;)

toshi
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Why would I want to create a function for tracking messages? I am glad you asked. As with most monotonous/routine tasks, human error tends to creep in after doing the same task over and over again. By creating a function, you load the function once…
Hi all.   The other day I had to change the passwords for a bunch of users on the fly. Because they were so many, I decided to do it in an automated way and I would like to share it with you all.   If you are not doing it directly in a Domain Co…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now