如何使用 PowerShell 向文件追加数据

  1. PowerShell 中 Add-Content 的基本语法
  2. 在 PowerShell 中使用 Add-Content 向文件附加文本
  3. 在 PowerShell 中使用 (`n) 运算符在新行上附加数据
  4. 在 PowerShell 中使用 Add-Content 命令将一个文件的内容添加到另一个文件
  5. 在 PowerShell 中使用 Add-Content 命令向只读文件附加数据
如何使用 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>]

在 PowerShell 中使用 Add-Content 向文件附加文本

例如,您在目录中拥有 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 将字符串 End of file 附加到当前目录中由 -Path 参数指定的文件的末尾。

输出:

Example illustration about appending text to End of file

在 PowerShell 中使用 (`n) 运算符在新行上附加数据

要在新行上将数据附加到文件中,请使用换行符运算符 (`n)。

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

输出:

Example illustration about appending text to End of file

Second line starts here…

在 PowerShell 中使用 Add-Content 命令将一个文件的内容添加到另一个文件

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 中。

PowerShell 中的 Add-Content cmdlet 将由 -Value 参数指定的源文件的内容附加。

当文件不存在时,Add-Content 命令将创建一个新文件并复制内容。

在 PowerShell 中使用 Add-Content 命令向只读文件附加数据

# 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