Teoman shipahi
Teoman shipahi

Reputation: 23062

Powershell does not keep variable reference until I set breakpoint

I wrote a small utility function in powershell to get JavaVersion.

function GetJavaVersion(){
    start-process  java  -ArgumentList "-version" -NoNewWindow -RedirectStandardError .\javaver.txt
    $javaver = Get-Content .\javaver.txt
    #just wait here for file to get released.
    Start-Sleep -s 5
    Remove-Item .\javaver.txt -Force 
    return $javaver;
}

If I run this code as following;

GetJavaVersion

It just does not print anything on console.

But if I set break point at $javaver = Get-Content .\javaver.txt line, and go step by step it prints out content as expected.

My PSVersion 5.1.14393.1358.

What I am missing here?

Upvotes: 1

Views: 29

Answers (1)

briantist
briantist

Reputation: 47812

Start-Process is not synchronous, so what likely happens is that the java process doesn't finish or write anything to the file by the time you read it a few milliseconds later.

By setting a breakpoint you give the java process time to finish before reading the file.

Use the -Wait parameter of Start-Process so that it waits for java to exit.

If you had put your sleep before reading it would probably work, but it's not really the right way to do that.

You also shouldn't need any kind of sleep after reading it before deleting it. Get-Content doesn't leave the file open.

Upvotes: 1

Related Questions