0

我正在尝试从我的 java 控制台应用程序执行一个 powershell 脚本,我能够使用以下命令使其工作:

Process p = Runtime.getRuntime().exec("cmd.exe /c start cd "+dir+" & start cmd.exe /k \"Powershell C:\\runscript.ps1 args\"",null,dir);
p.waitFor();

在我的 powershell 脚本中,我有以下代码片段,它在循环中被调用,

    Start-Process -FilePath $RunLocation -ArgumentList $args -wait -NoNewWindow -RedirectStandardOutput $OutputFile

$output = Get-Content $OutputFile| out-string   
    if(!($output.toLower().contains("failed"){
        Remove-Item $outLogFile
}

如果我打开命令提示符并准确复制exec(...)命令中的内容,它运行良好,但是,当我在我的 Java 应用程序中运行它时,似乎-wait我的 powershell 脚本中的 被忽略了,下一行(即检查和删除日志)运行,我什至已经在我的powershell中添加了几秒钟的睡眠时间Start-Process,这有效,但我希望有更好的方法。

我得到的错误是在powershell脚本中(这仅在我从我的Java应用程序运行它时发生,-wait等待启动过程完成,然后在直接从命令提示符运行时继续......):

Remove-Item : Cannot remove item D:\adhoc\logs\2016-06\output38844448.out: The process cannot access the file
'D:\adhoc\logs\2016-06\output38844448.out' because it is being used by another process.
At C:\runscript.ps1:91 char:3
+         Remove-Item $OutputFile
+         ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\adhoc\log...4448.out:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

当我使用 Java 应用程序运行它时,为什么-wait我的 powershell 脚本中的 不起作用runtime().exec

4

0 回答 0