Cannot move file after long running task

时间:2019-04-23 15:19:42

标签: powershell

I have a windows powershell script executed by Windows Task Scheduler. The powershell code starts an executable cli program (java), which creates it's own logfile, then when finished my powershell script tries to rename the file then upload it to a remote server. However, I'm finding that it only successfully uploads the file ever 3rd or 4th execution and am not sure why. The history in task scheduler provides no details as to what might have happened (file lock?). Any ideas on how I can solve this? Here is a basic example of what I'm doing:

$old_log_name = "old_logfilename"
$new_log_name = "new_logfilename"
C:\path\to\my-java-program.exe -pass -some -options
Move-Item -Path $old_log_name -Destination $new_log_name
gsutil cp $new_log_name gs://cool-bucket-with-cf

I'm certain that the problem is with renaming the file, and not with uploading it, because can see so in windows file explorer. Should I be checking to see if the file is available to be renamed or not?

Edit (revised code based on comments below):

$app_version = "4.5.7"
$now = get-date
$now = $now.ToString("yyyyMMddhhmm")
$old_log_name = "D:\myapp_$app_version.log"
$new_log_name = "D:\myapp_servername_$app_version.$now.log"
$arguments = "-a -c C:\myapp\config\Stage-$app_version.xml"
Start-Process C:\myapp\bin\4.5.7\myapp.exe -ArgumentList $arguments -NoNewWindow -Wait
Move-Item -Path $old_log_name -Destination $new_log_name
gsutil cp $new_log_name gs://path-to-mybucket

1 个答案:

答案 0 :(得分:1)

为什么不使用Java程序启动进程,所以它等待它退出?

$old_log_name = "old_logfilename"
$new_log_name = "new_logfilename"
Start-Process C:\path\to\my-java-program.exe -ArgumentList "your options" -NoNewWindow -Wait
Move-Item -Path $old_log_name -Destination $new_log_name
gsutil cp $new_log_name gs://cool-bucket-with-cf

更新
由于这是一项计划任务,因此您需要添加一个新的事件日志,以便从脚本中记录事件(您需要对此具有管理权限):

New-EventLog -LogName Application -Source TheScriptThatCallsMyJavaProgram

然后,将Start-Process调用替换为以下内容(EventId在这里是随机的):

Write-EventLog -LogName Application -Source TheScriptThatCallsMyJavaProgram -EventId 3001 -Message "my-java-program.exe is about to start" # This logs the start of the program
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "C:\path\to\my-java-program.exe"
$pinfo.Arguments = "your options"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
Write-EventLog -LogName Application -Source TheScriptThatCallsMyJavaProgram -EventId 3002 -Message "my-java-program.exe is exited" # This logs the end of the program