Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 8583

Powershell script works fine when fun from powershell console, but does not when run from batch file

$
0
0

I'm trying to run my powershell script from a batch file but I can't seem to get it to perform the same way when doing that.

If I run my powershell script from powershell console it works fine, if I run it form a batch file it doesn't work. The powershell script starts up a program called console, watches a folder for changes, and then backs up that folder when there are changes, it also listens for when the conlole program is closed and cleans itself up.

When running from a batch file, the batch file starts up the script using the powershell command, and the script does then still start the console application, and i see output for the register events, but then when a file is changed or added to the watched folder, nothing happens. Yet it does still print out the statement for when the console application closes. I'm not quite sure how to debug it :/

Sorry I don't know how to format the code on here, but I can send the file to someone if that's easier.

 

#edit this to the location of the console exe
$consoleExe = 'C:\Program Files (x86)\Console2\Console.exe'

#change to the location you'd like to save the backups
$backupDir = 'C:\Saves Backup';

#folder to watch for changes
$folder = 'C:\MyScripts' # Enter the root path you want to monitor.

#the amount of time to wait before saving the backups (in milliseconds)
$timeAfterWhichToSave = 5000

#the time after which to go ahead and copy if another event doesn't take place in the allotted time (in milliseconds)
$timerTimeout = 20000

#the timer object to start when an event occurs. reset it if another event fires within
[System.Timers.Timer]$timer = New-Object System.Timers.Timer
$timer.Interval = $timerTimeout

#create the backup dir if it doesn't exist already
$backupDirExists = Test-Path $backupDir
if(!$backupDirExists) {
    write-host Creating backup dir at $backupDir because it does not exist
    New-Item `"$backupDir`" -ItemType Directory -Force
}
else {
    write-host Backup `"$backupDir`" already exists
}

#unregister events, in case they weren't unregistered properly before. Just error siliently if they don't exist
Unregister-Event ConsoleStopped -ErrorAction SilentlyContinue
Unregister-Event FileCreated -ErrorAction SilentlyContinue
Unregister-Event FileChanged -ErrorAction SilentlyContinue
Unregister-Event TimerTick -ErrorAction SilentlyContinue

#start the console process
Write-Host Starting console process...
$consoleProcess = Start-Process "$consoleExe" -PassThru

#register to listen for when the console stops
Register-ObjectEvent $consoleProcess Exited -SourceIdentifier ConsoleStopped -Action {
    Write-Host Console stopped

    #unregister events
    Unregister-Event ConsoleStopped -ErrorAction SilentlyContinue
    Unregister-Event FileCreated -ErrorAction SilentlyContinue
    Unregister-Event FileChanged -ErrorAction SilentlyContinue

    if(!$timer.Enabled) {
        Unregister-Event TimerElapsed -ErrorAction SilentlyContinue
        Remove-Item $timer
    }

    Remove-Item $fsw
    Remove-Item $consoleProcess
}

#watch all files/folders
$filter = '*.*'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'DirectoryName, FileName, LastWrite'}

#register for FileCreated event
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    doStuff($Event)
}

#register for FileChanged event
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
    doStuff($Event)
}

function doStuff($event)
{
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' in '$folder' was $changeType at $timeStamp" -fore green

    if(!$timer.Enabled) {
        Write-Host Starting save timer
        Register-ObjectEvent $timer Elapsed -SourceIdentifier TimerElapsed -Action $TimerAction
        $timer.Start()
        Out-File "$backupDir\backup.log" -Append -Force -InputObject "A request for a backup created at $timeStamp"
    }
    else {
        Write-Host A backup has already been request
    }
}

$TimerAction =
{
    Write-Host Time to save!

    $timer.Stop()
    Unregister-Event TimerElapsed -ErrorAction SilentlyContinue

    #get the console process to see if it's running
    $consoleRunning = Get-Process "*console*" -ErrorAction SilentlyContinue

    #if console isn't running, remove the timer
    if($consoleRunning -eq $null) {
        Write-Host Console is no longer running, remove the timer but continue with backup
        Remove-Item $timer
    }

    backupSave
}

function backupSave ()
{
    Write-Host Starting backup...
    $timestamp = Get-Date -Format o | foreach { $_ -replace ":", "." }
    Copy-Item $folder "$backupDir\backup_$timestamp" -Recurse -Force
}

Viewing all articles
Browse latest Browse all 8583

Trending Articles