Solved

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

Posted on 2014-12-05
9
396 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_
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Ready to trade in that old firewall?

Whether you need to trade-up to a shiny new Firebox or just ready to upgrade from whatever appliance you're using now, WatchGuard has the right appliance for you! Find your perfect Firebox today with appliance sizing tool!

 
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
 

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

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

628 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