script_jr
script_jr

Reputation: 15

Powershell script - break loop

Giving this little script in powershell:

$index = 1
$file = "C:\Users\myfile"

while ($index -le 100000)
{
    $init_size = Write-Host((Get-Item $file).length/1KB)
    <here is my command which populates $file>
    $final_size = Write-Host((Get-Item $file).length/1KB)
    $index ++
    sleep 5
    If ($final_size -eq $init_size) {break}
}

I don't understand why it breaks even if the init_size is different from the final_size.

Any suggestions?

Upvotes: 0

Views: 52

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Write-Host writes directly to the screen buffer and doesn't output anything, so the value of both $init_size and $final_size are effectively $null when you reach the if statement.

Do Write-Host $variable after assigning to $variable and it'll work:

$index = 1
$file = "C:\Users\myfile"

while ($index -le 100000) {
    $init_size = (Get-Item $file).Length / 1KB
    Write-Host $init_size

    <here is my command which populates $file>

    $final_size = (Get-Item $file).Length / 1KB
    Write-Host $final_size

    $index++

    sleep 5

    If ($final_size -eq $init_size) { break }

}

Calling Write-Host on the results of the assignment expression itself would work too:

Write-Host ($init_size = (Get-Item $file).Length / 1KB)

Upvotes: 2

Related Questions