Search code examples
powershellconditional-statementsverbose

Why Write-Verbose messages don't appear from conditions


I'm trying to receive Verbose messages of every sorting step and run my script with -Verbose key, but I don't receive any verbose message from the conditionals (loops). I receive my messages only if I call them outside the conditionals. Please help

    [CmdletBinding()]
    param()
    set-location "\test folder"
    $listOfItems = Get-ChildItem | Select-Object -Property Name, Mode, LastWriteTime, @{label = "FileSize (MB)";expression = {$_.Length/1024/1024}}
    $bufferItem = 0
    for ($i = $listOfItems.Length - 1; $i -eq 0; $i--) {
        for ($j = 0; $i -lt $i; $j++) {
            if ($listOfItems[$j]."FileSize (MB)" -gt $listOfItems[$j + 1]."FileSize (MB)") {            
                Write-Verbose -Message "Transfer the value of the buffer variable to the element below the list"
                continue
            }
            elseif ($listOfItems[$j]."FileSize (MB)" -lt $listOfItems[$j + 1]."FileSize (MB)") {
                $bufferItem = $listOfItems[$j]
                $listOfItems[$j] = $listOfItems[$j + 1]
                $listOfItems[$j + 1] = $bufferItem
            }
            Write-Verbose -Message "Transfer the value of the buffer variable to the element below the list"
        }
    }

Solution

  • There's a bug in your inner loop condition:

    for ($j = 0; $i -lt $i; $j++) {
    

    Since $i -lt $i will never evaluate to $true, the inner loop body won't ever execute, and no Write-Verbose statement is ever reached.

    Fix the loop condition and you'll find Write-Verbose works perfectly fine in conditional statements.