Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2014-12-05
9
Medium Priority
?
446 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
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!

 
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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

In previous parts of this Nano Server deployment series, we learned how to create, deploy and configure Nano Server as a Hyper-V host. In this part, we will look for a clustering option. We will create a Hyper-V cluster of 3 Nano Server host nodes w…
In this post, I will showcase the steps for how to create groups in Office 365. Office 365 groups allow for ease of flexibility and collaboration between staff members.
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…
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 anti-spam), the admin…

916 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