
cmdlet
Out-File is a cmdlet provided by Powershell core libraries. This cmdlet provides features to write created output into a file in the file system. In this tutorial, we will look at different ways to write output into a file with Out-File
and Export-CSV
cmdlets.
Out-File是Powershell核心库提供的cmdlet。 此cmdlet提供的功能可将创建的输出写入文件系统中的文件。 在本教程中,我们将探讨使用Out-File
和Export-CSV
cmdlet将输出写入文件的不同方法。
写入文件 (Write Into A File)
One of the basic usage scenario of out-file is writing the output into a file without changing it. In this example we will write the output of Get-Process
command into a file named process.txt
by piping it. The file name can be specified as full path like C:\user\process.txt
外文件的基本使用方案之一是将输出写入文件而不更改它。 在此示例中,我们将通过管道将Get-Process
命令的输出写入名为process.txt
的文件中。 可以将文件名指定为完整路径,例如C:\user\process.txt
PS> Get-Process | Out-File process.txt

追加到现有文件(Append Into Existing File)
If we just want to add new lines and do not want to remove existing data we should add new data with -Append
option like below.
如果我们只想添加新行而不希望删除现有数据,则应使用-Append
选项添加新数据,如下所示。
PS> Get-Process | Out-File -Append process.txt
写为CSV (Write As CSV)
We can write created output into a file is CSV format. CSV format delimits the columns with comma. We will use Export-Csv
cmdlet for this operation. This will take more time than raw write into file because row will be separated and each column will be delimited with command.
我们可以将创建的输出写入CSV格式的文件中。 CSV格式以逗号分隔列。 我们将使用Export-Csv
cmdlet进行此操作。 这将比原始写入文件花费更多的时间,因为行将被分隔并且每列将由命令定界。
PS> Get-Process | Export-Csv test.txt

写入文件和控制台 (Write Both File and Console)
Another most used feature is while writing output into a file printing in the console too. This will provide verbose information about output. We will use Tee-Object
which is inherited from Linux operating system.
另一个最常用的功能是在控制台中将输出写入文件打印时。 这将提供有关输出的详细信息。 我们将使用从Linux操作系统继承的Tee-Object
。
In this example we get dir
command output into console and file named dirs.txt
在此示例中,我们将dir
命令输出输出到控制台和名为dirs.txt
文件中
PS> Dir | Tee-Object -f dirs.txt

翻译自: https://www.poftut.com/how-to-output-to-a-file-in-powershell-with-out-file-and-export-csv-cmdlet/
cmdlet