Link to home
Start Free TrialLog in
Avatar of WeTi
WeTi

asked on

Powershell Try and Catch.

Dear expert

See script code below:
$serverlist = Get-Content -Path 'c:\Scripts\serverlistOP.txt'
try{
foreach ($server in $serverlist) {
$server
query user /server:$server
}
}
catch{
"$Server do not have users"
}

Open in new window


Error return like this:
query : No User exists for *
At line:5 char:1
+ query user /server:$server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
And this:
query : Error 0x000006BA enumerating sessionnames
At line:5 char:1
+ query user /server:$server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Error 0x000006B...ng sessionnames:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Error [1722]:The RPC server is unavailable.
the RPC error in catch, I would like to show in catch message, RPC is unavailable, and  query : No User exists for * I want to show text: No users currently login now.

How do I corret show those?

Thanks
Avatar of ste5an
ste5an
Flag of Germany image

query does not return an error you can catch. It returns text. So you need to pack this into a variable and parse it.

Take also a look at Get-UserSession.
Avatar of WeTi
WeTi

ASKER

The get-usersession worked well, but there is no easier way? It seems alot of codes.
Avatar of WeTi

ASKER

I would like to if it found a return text with begin of the line: No User exist return only this line to show
Based on my function in https://www.experts-exchange.com/questions/29151406/Powershell-Parsing-quser-command.html
Function Get-UserSession {
[CmdletBinding()]
Param(
	[Parameter(Position=0, ValueFromPipeline=$true)]
	[String[]]$ComputerName = $ENV:ComputerName
)
	Process {
		$ComputerName | ForEach-Object {
			Try {
				Write-Verbose "Processing $($_) ..."
				$out = [ordered]@{}
				$out['ComputerName'] = $_
				$out['IPAddress'] = ([System.Net.Dns]::GetHostAddresses($_) | Where-Object {$_.AddressFamily -eq 'InterNetwork'})[0].IPAddressToString
				$output = & 'C:\Windows\system32\query.exe' user /server:$_
				If ($output -like '*No User exists*') {
					Write-Warning "[$($_)] $($output -join ' ')"
				} ElseIf ($output -like '*Error*') {
					Throw "[$($_)] $($output -join ' ')"
				} Else {
					$output |
						Select-Object -Skip 1 |
						Where-Object {$_ -match '(?<Current>.)(?<UserName>.{20})(?<SessionName>.{16})(?<ID>.{7})(?<State>.{8})\s+(?<IdleTime>\S+)\s+(?<LogonTime>.*)'} |
							ForEach-Object {
								ForEach ($prop in 'UserName', 'SessionName', 'ID', 'State', 'IdleTime', 'LogonTime') {$out[$prop] = $Matches[$prop].Trim()}
								[PSCustomObject]$out
							}
				}
			} Catch {
				$PSCmdlet.WriteError($_)
			}
		}
	}
}

$serverlist = Get-Content -Path 'c:\Scripts\serverlistOP.txt'
$serverlist | Get-UserSession

Open in new window

Avatar of WeTi

ASKER

ok still the question is how to handle errors:
query.exe : No User exists for *
At line:14 char:15
+                 $output = & 'C:\Windows\system32\query.exe' user /server:$_
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
query.exe : No User exists for *
At line:14 char:15
+                 $output = & 'C:\Windows\system32\query.exe' user /server:$_
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
query.exe : Error 0x000006BA enumerating sessionnames
At line:14 char:15
+                 $output = & 'C:\Windows\system32\query.exe' user /server:$_
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Error 0x000006B...ng sessionnames:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Error [1722]:The RPC server is unavailable.
query.exe : Error 0x000006BA enumerating sessionnames
At line:14 char:15
+                 $output = & 'C:\Windows\system32\query.exe' user /server:$_
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Error 0x000006B...ng sessionnames:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Error [1722]:The RPC server is unavailable.

Open in new window

The code is shorter now, and with $serverlist | Get-UserSession | ft Can i see the list better.
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of WeTi

ASKER

Wonderful thanks again, "-ErrorAction SilentlyContinue Im not going to need it, cause it ignored also those no user logged messages.