0

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?

1 Answer 1

2

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

Comments

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.