0

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 

}
1
  • "only first and second condition is triggered" — Get-ChildItem $folderPath either -eq $null or -ne $null; (barring a race condition) there is no third possibility in which your else would be executed. "when i tried ... i got error message" — What is the error and from where was it thrown? It'd be better to assign Get-ChildItem $folderPath to a variable then test if it's empty when deciding what to output. Also, see How to test for $null array in PowerShell for why you'd want to write those comparison as $null -ne (gci $folderPath). Commented Mar 17, 2022 at 10:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

well your solution is perfect but my problem is the fact that i need to use this kind of template to solve it : #Script template function listChildFolder($folderPath) { #write your script here return ... }
@bobmar Ok, I have added another solution without using try{..} catch{..} for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.