I would suggest doing it like this using a flag file.
Create a Start.bat file.
del C:\temp\scripts\stop.flg
start powershell.exe -WindowStyle Hidden -File C:\temp\Scripts\MyScript.ps1
Create a Stop.bat file.
echo stop > C:\temp\scripts\stop.flg
Your script file would look like this. Since it won't have a window to view the output, you should create a log file where you can document key processing events.
$log = "C:\Temp\Scripts\MyScript.log"
$StopFlag = "C:\temp\scripts\stop.flg"
"{0} - MyScript starting." -f (Get-Date) | Out-File -FilePath $log -Append
while ($true) {
"{0} - Main loop executing.." -f (Get-Date) | Out-File -FilePath $log -Append
# application code goes here.
Start-Sleep -Seconds 5 # Sleep for some period
if (Test-Path $StopFlag) {
"{0} - Stop flag detected." -f (Get-Date) | Out-File -FilePath $log -Append
remove-item $StopFlag
break
}
}
"{0} - MyScript ending." -f (Get-Date) | Out-File -FilePath $log -Append