0

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?

2
  • Well, first get rid of the > $null and break in the catch section to have a look at the exception that could be thrown ($_.Exception). The "return $true" won't help either keeping your loop going. Return breaks out of your function and if you are not in a function out of your script. Commented May 8, 2016 at 22:31
  • You´re right. I have input all the code into the function and now it can run in infinite loop. Commented May 12, 2016 at 19:48

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you were right about not using return. Still learning coding. To run it in infinite I followed @MartinMaat comment.

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.