Solved

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

Posted on 2014-12-05
9
340 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

Utilizing an array to gracefully append to a list of EmailAddresses
A brief introduction to what I consider to be the best editor for PowerShell.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

803 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