Home > Blockchain >  Powershell doesnt shows else condition when get error
Powershell doesnt shows else condition when get error

Time:03-17

when i tried to run the script only first and second condition is triggered when i tried for "e.g D:\random " where random folder is not exists, i got error message instead of triggering 3rd conditional "else"

function listChildFolder($folderPath) 
{

    #write your script here
    $folderPath = Read-Host "input"
    
    if ((Get-ChildItem $folderPath) -ne $null)
        { $folderPath| Get-ChildItem |Sort-Object -Property LastWriteTime -Descending |Format-Table name }

    elseif ((Get-ChildItem $folderPath) -eq $null)
        { "Folder Empty" }
    else {"Error: <Error message>"}
        
  
    return 

}

CodePudding user response:

Since Get-ChildItem throws a terminating error when the folder path does not exist, the function will end there and the rest of the elseif or else conditions are never executed.

I would suggest doing this in a try{..} catch{..} so you can capture exceptions like that:

Something like

function listChildFolder {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$folderPath
    )    

    # capture the terminating error message when the path does not exist
    # by specifying -ErrorAction Stop
    try {
        # since we do not add switch '-File' or '-Directory', 
        # the Get-ChildItem cmdlet will return both types
        $filesAndFolders = Get-ChildItem -Path $folderPath -ErrorAction Stop
        # next, find out if we found any files or folders in the path
        # the '@()' forces the $filesAndFolders variable into an array, so we can use the .Count property
        if (@($filesAndFolders).Count) {
            $filesAndFolders | Sort-Object LastWriteTime -Descending | Select-Object Name
        }
        else {
            Write-Host "No files or subfolders found in '$folderPath'"
        }
    }
    catch {
        Write-Warning "Error: $($_.Exception.Message)"
    }
}


$folderPath = Read-Host "Please enter a folder path"
# call the function
listChildFolder $folderPath

Another recommendation is that you use the PowerShell Verb-Noun naming convention for your function

  • Related