如何使用 PowerShell 將數據附加到文件

  1. PowerShell 中 Add-Content 的基本語法
  2. 使用 Add-Content 將文本附加到 PowerShell 中的文件
  3. 使用 (`n) 操作符在 PowerShell 中的新增行附加數據
  4. 使用 Add-Content 命令將一個文件的內容添加到另一個文件在 PowerShell 中
  5. 使用 Add-Content 命令將數據附加到只讀文件在 PowerShell 中
如何使用 PowerShell 將數據附加到文件

Add-Content 命令在 PowerShell 中將內容添加到文件中。我們可以在命令中指定內容或使用 Get-Content 來獲取文件的內容以進行附加。

Add-Content Cmdlet 將文本附加到文件或將字符串附加到文件。

PowerShell 中 Add-Content 的基本語法

Windows PowerShell 中的 Add-Content Cmdlet 將內容附加到文件並將文本附加到文件。

Add-Content
[-Path] <string[]>
[-Value] <Object[]>
[-PassThru]
[-Filter <string>]
[-Include <string[]>]
[-Exclude <string[]>]
[-Force]
[-Credential <pscredential>]
[-WhatIf]
[-Confirm]
[-NoNewline]
[-Encoding <Encoding>]
[-AsByteStream]
[-Stream <string>]
[<CommonParameters>]

使用 Add-Content 將文本附加到 PowerShell 中的文件

例如,您在目錄中有 Get-DateFile.txt 文本文件。

使用 Get-DateFile.txt 創建新文件,並添加一些測試數據。

Get-DataFile.txt:

Example illustration about appending text to
Add-Content -Path .\Get-DateFile.txt "End of file"

Add-Content Cmdlet 將指定的 -Path 參數的文件末尾附加字符串 End of file

輸出:

Example illustration about appending text to End of file

使用 (`n) 操作符在 PowerShell 中的新增行附加數據

要將數據附加到文件的新行中,使用新行操作符 (`n)。

Add-Content -Path .\Get-DateFile.txt "`nSecond line starts here..."

輸出:

Example illustration about appending text to End of file

Second line starts here…

使用 Add-Content 命令將一個文件的內容添加到另一個文件在 PowerShell 中

Add-Content 命令會將一個文件的內容附加到另一個文件。

它會讀取並將文件內容分配給變量,然後將內容寫入目標文件。

Add-Content 命令在添加文本到文件時,如果文件不存在,會創建一個新文件。

# Read file contents to variable
$sourceFileContent = Get-Content -Path .\GetFileProperties.txt 

# This line will append the content of one file to another file
# If the file does not exist, the Add-Content command will create a new file
Add-Content -Path .\Destination_File.txt -Value $sourceFileContent

要將一個文件的內容附加到另一個文件,PowerShell 中的 Get-Content Cmdlet 獲取由 Path 參數指定的文件內容。

然後,它會讀取文件內容並將其存儲在變量 $sourceFileContent 中。

Add-Content Cmdlet 在 PowerShell 中附加由 -Value 參數指定的源文件內容。

Add-Content 命令如果文件不存在將創建新文件並複製內容。

使用 Add-Content 命令將數據附加到只讀文件在 PowerShell 中

# Create a new file
New-Item -Path .\TempROFile.txt -ItemType File

# Set file as read-only
Set-ItemProperty -Path .\TempROFile.txt -Name IsReadOnly -Value $True 

# Get file details
Get-ChildItem -Path .\TempROFile.txt  

# Appends the line to file
Add-Content -Path .\TempROFile.txt -Value 'End of File' -Force

第一個命令使用 PowerShell 的 New-Item Cmdlet 創建一個新文件。

PowerShell 中的 Set-ItemProperty 命令用於將指定文件的 IsReadOnly 屬性設置為 true。

PowerShell 中的 Get-ChildItem 命令獲取指定文件的詳細信息,如 NameLastWriteTimeLengthmode

Add-Content Cmdlet 將一行附加到由 -Path 參數指定的只讀文件。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

相關文章 - PowerShell File