2017-01-11 36 views
0

我知道Powershell在腳本退出之前不會釋放文件。在我的腳本,我寫一個新的文件,因爲這:Powershell發佈文件

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

我如何可以釋放這個文件,所以我可以在後面的腳本讀?

回答

1

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.