在 PowerShell 中将多个文本文件合并为一个
在 PowerShell 中将多个文本文件合并为一个可以使用 PowerShell 中的 Get-Content 和 Set-Content cmdlet 来完成。
将文件连接成一个文件是必要的,原因有多种,包括数据整合和简化文件管理,将文件组合成一个文件以减少需要存储的文件数量。
PowerShell 中的 Get-Content cmdlet 获取文件的内容,并使用 Set-Content 将内容写入文件中。
在本文中,我们将讨论如何使用 PowerShell 中的 Get-Content 和 Set-Content cmdlet 将多个文本文件合并为一个文件。
PowerShell 将文件连接成一个
要将多个文本文件编译为一个文件,请使用 Get-Content cmdlet 读取文本文件的内容并将内容传递给 Set-Content cmdlet,后者写入输出到单个文件。
让我们考虑一下,Logs 文件夹包含三个文件 Log1.txt、Log2.txt 和 Log3.txt。这些文件包含事件日志。
# Get the items from the folder
Get-ChildItem -Path D:\Logs\
# Get the content of Log1.txt file1
Get-Content -Path D:\Logs\Log1.txt
# Get the content of Log2.txt file2
Get-Content -Path D:\Logs\Log2.txt
# Get the content of Log3.txt file3
Get-Content -Path D:\Logs\Log3.txt在上面的 PowerShell 脚本中,PowerShell 中的 Get-ChildItem cmdlet 从指定的文件夹路径获取项目。使用Get-Content命令,它获取文件的内容并将其显示在终端上。
要将多个文件合并为一个文件,例如 (Log1.txt + Log2.txt + Log3.txt),请运行以下包含 Get-Content 和 Set-Content cmdlet 的 PowerShell 脚本。
# Concatenate multiple files using the Get-Content and write to single file
Get-Content -Path D:\Logs\*.txt | Set-Content -Path D:\Logs\Log_merge.txt
# Get the content of merged file
Get-Content -Path D:\Logs\Log_merge.txt在上面的 PowerShell 脚本中,Get-Content cmdlet 使用 Path 参数从指定目录路径获取所有 .txt 文件的内容,将它们合并在一起并将它们传递给 Set-Content 以将输出写入一个文件。
将多个文件组合成一个文件的输出包含该文件夹中所有可用文件的内容。
要连接不同扩展名的多个文件(例如 *.txt、*.log 等),请运行以下命令。
# Concatenate multiple files using the Get-Content and write to single file
Get-Content -Path D:\Logs\*.txt, D:\Logs\*.log | Set-Content -Path D:\Logs\Log_merge.txt在上面的PowerShell脚本中,Get-Content从多个文件路径获取内容,读取.txt和.log文件的内容,并将它们组合成一个字符串。 Set-Content 命令使用组合文件的内容并写入一个文件。
酷提示:如何在 PowerShell 中比较两个字符串!
结论
希望上述在PowerShell中使用Get-Content和Set-Content cmdlet将多个文本文件合并到PowerShell中的一个文件的文章对您有所帮助。
您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

