本文介紹使用PowerShell來寫文件時,如何阻止系統自動覆蓋已有的文件。
我們在使用腳本進行文件處理的時候,我們可能不希望使用Ou-File生成的文件覆蓋已有的文件。那么怎么實現呢?在Out-File這個CmdLet中,有沒有什么參數可以阻止Out-File不聲不響的覆蓋了已有的文件呢?
答案是-NoClobber參數。
NoClobber參數
在Out-File輸出到文件時,如果使用了-NoClobber參數,則系統遇到已有文件時,將無法執行成功。下面的例子展示了當d:/1.txt已經存在時,使用Out-File輸出內容到該文件時,系統將會報錯。
代碼如下:
PS C:/Users/spaybow> "" | Out-File d:/1.txt
PS C:/Users/spaybow> "" | Out-File d:/1.txt -NoClobber
Out-File : 文件“D:/1.txt”已經存在。
所在位置 行:1 字符: 14
+ "" | Out-File <<<< d:/1.txt -NoClobber
+ CategoryInfo : ResourceExists: (D:/1.txt:String) [Out-File], IO
Exception
+ FullyQualifiedErrorId : NoClobber,Microsoft.PowerShell.Commands.OutFileC
ommand
另外需要說明的是:我們知道-Append參數用于指定將字符串附加到文件。如果同時指定了-Append 和 -NoClobber參數,會不會有沖突呢?答案是,系統會將字符串附加到文件。演示如下:
PS C:/Users/spaybow> "hello" | Out-File d:/1.txt
PS C:/Users/spaybow> "powershell" | Out-File d:/1.txt -NoClobber -Append
PS C:/Users/spaybow> type d:/1.txt
hello
powershell
關于PowerShell使用Out-File寫文件時禁止覆蓋已有文件,本文就介紹這么多,希望對您有所幫助,謝謝!
新聞熱點
疑難解答