PowerShell Set-Content 命令

  1. PowerShell 中的 Set-Content Cmdlet
  2. 使用 Set-Content Cmdlet 将文本内容写入单个文件
  3. 使用 Set-Content Cmdlet 替换多个文件中的文本内容
  4. 使用 Set-Content 通过管道传递文本内容
PowerShell Set-Content 命令

有时候,我们可能需要将相同的文本内容写入多个文本文件。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!"

使用 Set-Content Cmdlet 替换多个文件中的文本内容命令

这三个文件匹配模式 file* txt,这迫使命令匹配所有以 file 开头的文件。

输出:

使用 Set-Content Cmdlet 替换多个文件中的文本内容输出

使用 Set-Content 通过管道传递文本内容

并不总是需要指定 -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 文件。

输出:

使用 Set-Content 通过 PIPE 输出传递文本内容

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

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.