本文介紹使用PowerShell來寫文件時,如何阻止系統(tǒng)自動覆蓋已有的文件。
我們在使用腳本進(jìn)行文件處理的時候,我們可能不希望使用Ou-File生成的文件覆蓋已有的文件。那么怎么實現(xiàn)呢?在Out-File這個CmdLet中,有沒有什么參數(shù)可以阻止Out-File不聲不響的覆蓋了已有的文件呢?
答案是-NoClobber參數(shù)。
NoClobber參數(shù)
在Out-File輸出到文件時,如果使用了-NoClobber參數(shù),則系統(tǒng)遇到已有文件時,將無法執(zhí)行成功。下面的例子展示了當(dāng)d:\1.txt已經(jīng)存在時,使用Out-File輸出內(nèi)容到該文件時,系統(tǒng)將會報錯。
復(fù)制代碼 代碼如下:
PS C:\Users\spaybow> "" | Out-File d:\1.txt
PS C:\Users\spaybow> "" | Out-File d:\1.txt -NoClobber
Out-File : 文件“D:\1.txt”已經(jīng)存在。
所在位置 行: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參數(shù)用于指定將字符串附加到文件。如果同時指定了-Append 和 -NoClobber參數(shù),會不會有沖突呢?答案是,系統(tǒng)會將字符串附加到文件。演示如下:
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
關(guān)于PowerShell使用Out-File寫文件時禁止覆蓋已有文件,本文就介紹這么多,希望對您有所幫助,謝謝!
您可能感興趣的文章:- PowerShell Out-File指定文件編碼的方法
- PowerShell Out-File向只讀文件寫入內(nèi)容的方法
- PowerShell Out-File追加字符串到文件末尾的方法