Powershell 发布文件

Powershell Release file

我了解 Powershell 在脚本退出之前不会释放文件。在我的脚本中,我正在写入一个新文件,如下所示:

[System.IO.File]::WriteAllText("E:\Outline\newLocations.xml", $locationsContent)

如何释放此文件以便稍后在脚本中阅读?

WriteAllText方法不锁定文件。下面是一个创建新文本文件的示例,使用该方法写入它,然后从中读取,然后删除它。您也可以通过创建文件、写入文件来测试这一点,然后 PowerShell 仍然打开并尝试从 Windows 资源管理器中删除它。 类一般会有一个Dispose方法,如果需要释放实例。

New-Item "C:\temp\newLocations.txt" -ItemType File

Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        1/11/2017  12:16 PM              0 newLocations.txt

[System.IO.File]::WriteAllText("C:\temp\newLocations.txt", "test")

Get-Content "C:\temp\newLocations.txt"
test

Remove-Item "C:\temp\newLocations.txt"

get-item "C:\temp\newLocations.txt"
get-item : Cannot find path 'C:\temp\newLocations.txt' because it does not exist.