Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-12-05
9
Medium Priority
?
425 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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
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 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

A brief introduction to what I consider to be the best editor for PowerShell.
The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
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…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

705 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