Reputation: 123
I have this powershell script that trigger some instruction when a file is created in a certain directory. All works well, but I'm not able to close the powershell after that the action is done. How can I do that?
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\Autostrade\CartellaSFTP"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$uscita = 0
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "C:\Users\Autostrade\PHP Script Dati Telepass\log.txt" -value $logline
# Set up references to executable and script
$PhpExe = "C:\PHP\php.exe"
$PhpFile = "C:\Users\Autostrade\PHP Script Dati Telepass\script.php"
# Create arguments from Script location
# usually php.exe is invoked from console like:
# php.exe -f "C:\path\myscript.php"
#$PhpArgs = '-f "{0}"' -f $PhpFile
# Invoke, using the call operator
$PhpOutput = & $PhpExe $PhpFile
PhpOutput
$uscita = 1
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
#Register-ObjectEvent $watcher "Changed" -Action $action
#Register-ObjectEvent $watcher "Deleted" -Action $action
#Register-ObjectEvent $watcher "Renamed" -Action $action
while (!$uscita) {sleep 5}
exit
I tried using that "$uscita" variable to stop the while and exit, but it's not working. I tried also to put at the end of the action the exit command, but that is not working too
Upvotes: 1
Views: 31001
Reputation: 123
I edited the last part of my code in this way and now it works. So after the action, the script ends itself. Here's the code:
while (!$uscita) {
if($? -eq $false) {
exit
}
sleep 5}
Upvotes: 3
Reputation: 340
Offhand it looks like your 2nd to last line with the while is probably returning true, so it just sits in the sleep command.
Try this to test, it will return true if the last command completed successfully.
while (!$uscita) {write-output $?; sleep 5}
Upvotes: 0