Home > Software engineering >  Try Catch not working inside function / functions
Try Catch not working inside function / functions

Time:06-11

2 functions one calls the other.

The CATCH blocks in the function Export-LoggedOnUser are not being triggered when I leave either the $path parameter or the $ComputerName parameter NULL. The Export-LoggedOnUser function is calling the first function "Get-LoggedOnUser". It too will not trigger the catch block if I leave the $ComputerName Parameter null. I have written these in various ways and they both work as desired except the TRY/CATCH structures do not perform in either function.

The Typical error is some always some variation of a 'ParameterBindingValidationException' which is to be expected except that it is not being handled in the CATCH. I'm flummoxed. Gotta be something simple.

    function Get-LoggedOnUser{
     [CmdletBinding()]
          [Alias()]
          Param
          (
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
        [ValidateScript({Test-Connection -ComputerName $_ -Quiet -Count 1})]
        [ValidateNotNullOrEmpty()]
        [string[]]$ComputerName 
           )
Try{
  ForEach($computer in $ComputerName){
     $output = @{
     'ComputerName' = $computer;     }#OutputHashTable
     $output.UserName = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer -ErrorAction Stop).Username    
     [PSCustomObject]$output
     }
  }
Catch{
    Write-host 'You must enter a valid computername'
     }
  }

#New Function
function Export-LoggedOnUser{
    [CmdletBinding()]
    [Alias()]
   Param(
        [Parameter(Mandatory=$True)]
        [string]$Path,
        [Parameter(Mandatory=$True)]
        [string[]]$ComputerName
         )
    try{
     $loggedonuser = Get-LoggedOnUser -ComputerName $ComputerName -ErrorAction stop 
     
       }
    catch{
         Write-Host "You need to provide a Computername"
        }
    Try{
     $loggedonuser | Export-Csv -Path $Path -NoTypeInformation -ErrorAction Stop
     }
    Catch{
     Write-Host 'You must enter a valid path'
     } 
 }

CodePudding user response:

Christian,

If you want to test the $Computername parameter and provide an error message I'd drop the parameter validation and do the following:

Function Test {

Param (
  [Parameter(Mandatory=$False)]
    [String[]] $ComputerName
)

If ($Null -ne $ComputerName) {

  ForEach ($Computer in $ComputerName) {
        $GCIMArgs = @{Class        = 'Win32_ComputerSystem'
                      ComputerName = "$computer"
                      ErrorAction  =  'Stop'}

    Try   { $UserName = (Get-CIMInstance @GCIMArgs ).Username }
    Catch { "Error: $Computer is an invalid computer name!"   }

<# ----------------------------------------------------------- 
  | Place your code her to place $username in your PSObject!  |
   ----------------------------------------------------------- 
#>

  } #End ForEach

} #End If ($Null -ne $ComputerName)

Else { "You must supply a valid array of computer names..." }

} #End Function Test

#--------------------  Main Program ---------------------

Test @("DellXPS8920","Dellxps8700","JanetsLaptop")

If run as shown above you get this output:

Error: JanetsLaptop is an invalid computer name!

Which is correct for my lan since that laptop was not turned on.

If you just call TEST with out the array you get this:

You must supply a valid array of computer names...
  • Related