Okrx
Okrx

Reputation: 119

Powershell script does not run in infinite loop

I am trying to run this script in infinite loop:

$UNC = "\\pawelu\IELTS9"
$hostname = "pawelu"
$val = 1

start-transcript -path C:\Users\Administrator\Desktop\new.txt -append;

while($true) { 
Get-Date -format o;
start-sleep -s 3; write-host "UNC available... " -nonewline;
test-path $UNC;
$pingTest = test-connection -computername $hostname -count 1 -Quiet;  
write-host "ICMP is succesfull ... " $pingTest
write-host "Can write a file ... " -NoNewline
try {

$testPath = join-path $UNC ([IO.Path]::GetRandomFileName())
new-item -path $testPath -ItemType file -ErrorAction Stop > $null


add-content $testPath SampleText
return $true

}catch
    {return $false
    }
    finally{

         remove-item $testPath -ErrorAction SilentlyContinue
        }
}

However it stops after running one time. If I remove Try,catch and finally block it keeps on going after I stop it manually and that is want I want. Thus, I think the flaw is somewhere there but cannot figure it out. How do I make it this script to keep on running?

Upvotes: 0

Views: 3029

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

How do I make it this script to keep on running?

Stop making the script return.

Simply remove the return $true statement from the try block.

If you want the loop to continue even when an error occurs, remove return $false from the catch block as well

Upvotes: 2

Related Questions