Search code examples
windowspowershellbatch-filescheduled-taskswindows-server-2012

Powershell in a batch file running as a service issue


disclosure I'm a PHP/Linux developer that is having to get use to working in a Windows environment, so I very well my be missing something fundamental in the question. I've researched the heck out of this and can't seem to pinpoint a solution. Thanks for your help in advanced.

I have a batch file that calls a powershell script that doesn't work correctly when it is started by the window's task scheduler, but works perfectly when it is launched by hand.

Below is the Powershell script that the batch file is launching...

$WatchFolder = '\\networkshare\foldername' 
$Filter = '*.csv'
$fsw = New-Object IO.FileSystemWatcher $WatchFolder, $Filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters] 'LastWrite'}

Register-ObjectEvent $fsw Changed -SourceIdentifier SAS_Poll_FileChanged -Action {    
    $WatchFolder = '\\networkshare\foldername' 
    $OutputFolder_one = '\\networkshare\outputFolder_One'
    $OutputFolder_two = '\\networkshare\outputFolder_Two'

    $name = $Event.SourceEventArgs.Name

    $lock_file = $WatchFolder + '\.' + $name + '.lock'

    $test = (Test-Path "$lock_file")

    if ( $test ){
        return
    } else {
        Set-ExecutionPolicy -Scope CurrentUser Bypass
        Out-File -FilePath "$lock_file"
        Start-Process powershell -ArgumentList ".\General\PollingProcess-alone.ps1 $WatchFolder $MainFrameFolder $SASFolder $name $lock_file" -NoNewWindow
    }

}

I know the issue occurs at the following line...

Start-Process powershell -ArgumentList ".\General\PollingProcess-alone.ps1 $WatchFolder $MainFrameFolder $SASFolder $name $lock_file" -NoNewWindow

I know this b/c when the event is triggered ( when the script is launched via the task scheduler ), the lock file is created and then the process hangs.

I therefore think that the issue has something to do with path of second powershell script I'm calling, but I don't know how to fix it. I've tried using the full path of the second script, but haven't been able to make it work.

Just to give you some more context of the script, it is sort of important the the event process spins up a new powershell script b/c I need these scripts to run concurrently.


Solution

  • Pretty sure the problem is with your argument list, right now you are passing a single string with everything contained within it, change that to an array and things should work properly.

    so convert ".\General\PollingProcess-alone.ps1 $WatchFolder $MainFrameFolder $SASFolder $name $lock_file"

    to ".\General\PollingProcess-alone.ps1",$WatchFolder,$WatchFolder,etc..

    give that a shot and let us know if it works for you, also want to say that your code is impressive for being relatively new to PowerShell so kudos lol.