bob mar
bob mar

Reputation: 7

Powershell doesnt shows else condition when get error

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 

}

Upvotes: 0

Views: 111

Answers (1)

Theo
Theo

Reputation: 61068

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


As per your comment where you say you may not use try{..} catch{..}, there are other ways of course.

How about this:

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

    # test if the given folder path exists
    if (Test-Path -Path $folderPath -PathType Container) {
        # since we do not add switch '-File' or '-Directory', 
        # the Get-ChildItem cmdlet will return both types
        $filesAndFolders = Get-ChildItem -Path $folderPath
        # 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'"
        }
    }
    else {
        Write-Warning "Error: '$folderPath' does not exist"
    }
}


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

Upvotes: 1

Related Questions