PowerShell Set-Content Cmdlet
-
PowerShell 中的
Set-Content
Cmdlet -
使用
Set-Content
Cmdlet 將文本內容寫入單個文件 -
使用
Set-Content
Cmdlet 替換多個文件中的文本內容 -
使用
Set-Content
透過 PIPE 傳遞文本內容

有時,我們可能需要將相同的文本內容寫入多個文本文件。PowerShell 提供了一個有用的 cmdlet,可以通過命令行寫入文本內容。
在這篇文章中,我們將專注於 Set-Content
cmdlet。
PowerShell 中的 Set-Content
Cmdlet
Set-Content
cmdlet 寫入新的文本內容或替換文件中現有的文本。這更類似於 Linux 中的 >
操作符。
Set-Content
cmdlet 與 Add-Content
字符串處理 cmdlet 不同,後者是將文本附加到指定文件中。可以使用別名 sc
來表示 Set-Content
命令。
語法:
Set-Content
[-Path_to_file] <string[]>
[-Value] <Object[]>
[-PassThru]
[-Filter <string>]
[-Include <string[]>]
[-Exclude <string[]>]
[-Force]
[-Credential <pscredential>]
[-WhatIf]
[-Confirm]
[-NoNewline]
[-Encoding <Encoding>]
[-AsByteStream]
[-Stream <string>]
[<CommonParameters>]
該命令接受相當多的參數,其中一些的用途在以下部分中描述。
參數 | 描述 |
---|---|
-Path_to_file |
你可以指定一個現有的文本文件路徑或在給定路徑下創建一個新的文件。 |
-Value |
此參數用於傳遞你將要寫入的文本內容。 |
-Force |
-Force 參數替換只讀文件中的內容。 |
-Encoding |
目標文件的文本編碼默認設置為 utf8NoBOM 。 |
-Exclude |
需要在這次操作中排除的項目以字符串數組形式指定。 |
-Include |
這與 -Exclude 參數相對。此參數指定需要包含在 Set-Content 操作中的項目數組。 |
-PassThru |
當指定 PassThru 參數時,命令輸出已添加到文本文件的文本內容。 |
通常,-Value
參數通常用於指定寫入文件的文本內容。此外,你還可以從另一個對象中通過管道傳遞文本內容。
如果你將一個非字符串對象傳遞給 Set-Content
命令,它將首先將非字符串對象轉換為字符串,然後寫入文件。
使用 Set-Content
Cmdlet 將文本內容寫入單個文件
讓我們將文本內容寫入名為 sometext.txt
的文件,該文件目前不存在。因此,Set-Content 命令將首先創建此文件並寫入使用 -Value
參數傳遞的內容。
命令:
Set-Content -Path D:\codes\sometext.txt -Value "This should create a new file called sometext.txt and write this text to it..."
輸出:
使用 Set-Content
Cmdlet 替換多個文件中的文本內容
假設我們有三個文件 file1.txt, file2.txt, 和 file3.txt
。我們將用以下文本替換這三個文件的內容。
Hello, i would be appeared in all the three files!
在這種情況下,Set-Content
命令使用通配符字符來匹配給定的三個文件。
命令:
Set-Content -Path D:\codes\file*.txt -Value "Hello, i would be appeared in all the three files!"
這三個文件匹配由 file* txt
指定的模式,這強制命令匹配所有以 file
短語開頭的文件。
輸出:
使用 Set-Content
透過 PIPE 傳遞文本內容
不必總是指定 -Value
參數。相反,我們可以將文本對象通過管道傳遞給 Set-Content
,如下所示。
命令:
(Get-Content D:\codes\file1.txt).replace('all the three files!', 'file4.txt') | Set-Content D:\codes\file4.txt
Get-Content
cmdlet 從 file1.txt
文件中讀取文本內容。然後,它使用 replace
命令將 all the three files!
文本替換為 file4.txt
。
最後,構建的文本將被寫入 file4.txt
文件中。
輸出:
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.