PowerShell Out-File
cmdlet将输出发送到特定文件。 当需要使用其参数时,请使用此cmdlet代替重定向运算符(>
)。
语法1
Out-File [-FilePath] <string> [[-Encoding] {unknown | string | unicode | bigendianunicode | utf8 | utf7 | utf32 | ascii | default | oem}] [-Append] [-Force] [-NoClobber] [-Width <int>] [-NoNewline] [-InputObject <psobject>] [-WhatIf] [-Confirm] [<CommonParameters>]
语法2
Out-File [[-Encoding] {unknown | string | unicode | bigendianunicode | utf8 | utf7 | utf32 | ascii | default |oem}] -LiteralPath <string> [-Append] [-Force] [-NoClobber] [-Width <int>] [-NoNewline] [-InputObject <psobject>] [-WhatIf] [-Confirm] [<CommonParameters>]
以下是此cmdlet中使用的参数:
-FilePath 和 -LiteralPath - 这两个参数均用于指定命令中文件的路径。
-Encoding - 此参数指定文件中使用的字符类型。此参数的默认值为UTF8NoBOM
。以下是此参数可接受的值:
-Append - 此参数用于将输出添加到文件的末尾。
-Force - 此参数将覆盖现有的只读文件和只读属性。 它不会覆盖安全限制。
-NoClobber - 此参数防止覆盖具有相同名称的现有文件,并显示一条消息,指出该文件已存在。
-Width - 此参数指定每个输出行中的字符数。
-NoNewLine - 此参数指定写入文件的内容不以换行符结尾。
-InputObject - 此参数指定那些写入文件的对象。
-WhatIf - 此参数显示执行cmdlet将发生的情况。
-Confirm - 执行cmdlet之前,此参数提示确认。
示例1:
PS E:\xntutor\powershell> get-childitem | out-file -filepath "E:\xntutor\powershell\process.txt" PS E:\xntutor\powershell>
本示例中的命令将get-childitem
cmdlet的输出发送到文本文件,该文本文件使用-FilePath
参数在命令中指定了路径。
示例2:
PS E:\xntutor\powershell> get-childitem | out-file -filepath "E:\xntutor\powershell\process.txt" PS E:\xntutor\powershell> get-process | out-file -noclobber -filepath "E:\xntutor\powershell\process.txt" out-file : 文件“E:\xntutor\powershell\process.txt”已经存在。 所在位置 行:1 字符: 15 + ... t-process | out-file -noclobber -filepath "E:\xntutor\powershell\pro ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (E:\xntutor\powershell\process.txt:String) [Out-File], IOException + FullyQualifiedErrorId : NoClobber,Microsoft.PowerShell.Commands.OutFileCommand PS E:\xntutor\powershell>
本示例中的命令不会将get-process
cmdlet的输出发送到process.txt
文件,并且由于该文件已经存在,因此显示错误。 由于命令中使用-NoClobber
参数,因此无法覆盖文件process.txt
。
上面示例执行结果如下: