【问题标题】:Unable to re-write the file in powershell using Out-File无法使用 Out-File 在 powershell 中重写文件
【发布时间】:2018-01-04 20:55:01
【问题描述】:

我正在尝试编写一个 powershell 脚本来将命令的输出写入文件。它第一次运行得很好。当我重新运行脚本时,它会出现错误

Out-File : The process cannot access the file '//Filepath' because it is 
being used by another process.
+         (Invoke-Command -Session $s -ScriptBlock $command )| Out-File 
$file -For ...

代码块:

$command = { 
$x = (Get-Date).AddMinutes(-5).ToShortTimeString() ;
$y = "{0:HH:mm}" -f [datetime] $x ;
cd $path ;
dumplog ctisvr /bt $y /m "CSTAUniversalFailureConfEvent"
}
#$s = New-PSSession -ComputerName 
(Invoke-Command -Session $s -ScriptBlock $command )| Out-File $file -Force

【问题讨论】:

  • 听起来您有一个需要关闭的开放 IO 流。您可能需要检查进程监视器以​​查看该转储日志命令是否实际上仍然使您的文件处于打开状态。
  • 我只有一件事写入文件,即“Out-File $file -Force”。 Dumplog 只有开始和结束时间,因此不会进入无限循环。 Out-File 是否有任何命令来结束该流?

标签: powershell file-io out


【解决方案1】:

我的建议是这不是 PoSH 导致的问题,而是您正在使用的 dumplog 命令。有些程序不会锁定文件和那些会锁定文件的程序。没用过dumplog,这里只能推测。

因此,最好先检查 exe 和文件的进程状态,然后再对其进行任何操作。

就像在第一次序列化完成后简单地寻找转储日志进程一样,在重试之前杀死任何转储日志进程。

如果这是在文件共享上,您可以使用...

Get-SmbOpenFile

或者

openfiles

如果是本地的,您可以执行类似...

What file is open by a given program
Get-CimInstance Win32_Process -Filter "name = 'dumplog.exe'" | Format-List -Property *

Get the owner of the process
$ProcessId = Get-CimInstance Win32_Process -Filter "name = 'dumplog.exe'"
Invoke-CimMethod -InputObject $ProcessId -MethodName GetOwner

What process has a file locked or filter the results based on the file name:
($ProcessId = Get-CimInstance Win32_Process | where commandline -match 'CSTAUniversalFailureConfEvent')

Kill the process
Invoke-CimMethod -InputObject $ProcessId -MethodName Terminate

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 2020-07-01
    • 2014-10-29
    • 2023-02-24
    • 2016-12-25
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多