When you need to specify parameters for the output, use Out-File rather than the ... utf7 : Encodes in UTF-7 format. utf8 : Encodes in UTF-8 format.
Skiptomaincontent
Thisbrowserisnolongersupported.
UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport.
DownloadMicrosoftEdge
MoreinfoaboutInternetExplorerandMicrosoftEdge
Tableofcontents
Exitfocusmode
ReadinEnglish
Save
Tableofcontents
ReadinEnglish
Save
Feedback
Edit
Twitter
LinkedIn
Facebook
Email
Tableofcontents
Out-File
Reference
Module:
Microsoft.PowerShell.Utility
Sendsoutputtoafile.
Inthisarticle
Syntax
Out-File
[-FilePath]
[[-Encoding]]
[-Append]
[-Force]
[-NoClobber]
[-Width]
[-NoNewline]
[-InputObject]
[-WhatIf]
[-Confirm]
[]
Out-File
[[-Encoding]]
-LiteralPath
[-Append]
[-Force]
[-NoClobber]
[-Width]
[-NoNewline]
[-InputObject]
[-WhatIf]
[-Confirm]
[]
Description
TheOut-Filecmdletsendsoutputtoafile.ItimplicitlyusesPowerShell'sformattingsystemto
writetothefile.Thefilereceivesthesamedisplayrepresentationastheterminal.Thismeans
thattheoutputmaynotbeidealforprogrammaticprocessingunlessallinputobjectsarestrings.
Whenyouneedtospecifyparametersfortheoutput,useOut-Fileratherthantheredirection
operator(>).Formoreinformationaboutredirection,see
about_Redirection.
Examples
Example1:Sendoutputandcreateafile
Thisexampleshowshowtosendalistofthelocalcomputer'sprocessestoafile.Ifthefiledoes
notexist,Out-Filecreatesthefileinthespecifiedpath.
Get-Process|Out-File-FilePath.\Process.txt
Get-Content-Path.\Process.txt
NPM(K)PM(M)WS(M)CPU(s)IdSIProcessName
-------------------------------------
2922.3935.4010.98427649Application
5399.04113.960.00326640CcmExec
2796.62112.43113.00177209Code
TheGet-Processcmdletgetsthelistofprocessesrunningonthelocalcomputer.TheProcess
objectsaresentdownthepipelinetotheOut-Filecmdlet.Out-FileusestheFilePath
parameterandcreatesafileinthecurrentdirectorynamedProcess.txt.TheGet-Content
commandgetscontentfromthefileanddisplaysitinthePowerShellconsole.
Example2:Preventanexistingfilefrombeingoverwritten
Thisexamplepreventsanexistingfilefrombeingoverwritten.Bydefault,Out-Fileoverwrites
existingfiles.
Get-Process|Out-File-FilePath.\Process.txt-NoClobber
Out-File:Thefile'C:\Test\Process.txt'alreadyexists.
Atline:1char:15
+Get-Process|Out-File-FilePath.\Process.txt-NoClobber
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TheGet-Processcmdletgetsthelistofprocessesrunningonthelocalcomputer.TheProcess
objectsaresentdownthepipelinetotheOut-Filecmdlet.Out-FileusestheFilePath
parameterandattemptstowritetoafileinthecurrentdirectorynamedProcess.txt.The
NoClobberparameterpreventsthefilefrombeingoverwrittenanddisplaysamessagethatthe
filealreadyexists.
Example3:SendoutputtoafileinASCIIformat
Thisexampleshowshowtoencodeoutputwithaspecificencodingtype.
$Procs=Get-Process
Out-File-FilePath.\Process.txt-InputObject$Procs-EncodingASCII-Width50
TheGet-Processcmdletgetsthelistofprocessesrunningonthelocalcomputer.TheProcess
objectsarestoredinthevariable,$Procs.Out-FileusestheFilePathparameterandcreates
afileinthecurrentdirectorynamedProcess.txt.TheInputObjectparameterpassesthe
processobjectsin$ProcstothefileProcess.txt.TheEncodingparameterconvertsthe
outputtoASCIIformat.TheWidthparameterlimitseachlineinthefileto50charactersso
somedatamightbetruncated.
Example4:Useaproviderandsendoutputtoafile
ThisexampleshowshowtousetheOut-FilecmdletwhenyouarenotinaFileSystemprovider
drive.UsetheGet-PSProvidercmdlettoviewtheprovidersonyourlocalcomputer.Formore
information,seeabout_Providers.
PS>Set-Location-PathAlias:
PS>Get-Location
Path
----
Alias:\
PS>Get-ChildItem|Out-File-FilePathC:\TestDir\AliasNames.txt
PS>Get-Content-PathC:\TestDir\AliasNames.txt
CommandTypeName
---------------
Alias%->ForEach-Object
Alias?->Where-Object
Aliasac->Add-Content
Aliascat->Get-Content
TheSet-LocationcommandusesthePathparametertosetthecurrentlocationtotheregistry
providerAlias:.TheGet-LocationcmdletdisplaysthecompletepathforAlias:.
Get-ChildItemsendsobjectsdownthepipelinetotheOut-Filecmdlet.Out-Fileusesthe
FilePathparametertospecifythecompletepathandfilenamefortheoutput,
C:\TestDir\AliasNames.txt.TheGet-ContentcmdletusesthePathparameteranddisplaysthe
file'scontentinthePowerShellconsole.
Example5:Setfileoutputwidthforentirescope
Thisexampleuses$PSDefaultParameterValuestosettheWidthparameterforallinvocationsof
Out-Fileandtheredirectionoperartors(>and>>)to2000.Thisensuresthateverywhere
withinthecurrentscopethatyououtputtableformatteddatatofile,PowerShellusesalinewidth
of2000insteadofalinewidthdeterminedbythePowerShellhost'sconsolewidth.
functionDemoDefaultOutFileWidth(){
try{
$PSDefaultParameterValues['out-file:width']=2000
$logFile="$pwd\logfile.txt"
Get-ChildItemEnv:\>$logFile
Get-Service-ErrorActionIgnore|Format-Table-AutoSize|Out-File$logFile-Append
Get-Process|Format-TableId,SI,Name,Path,MainWindowTitle>>$logFile
}
finally{
$PSDefaultParameterValues.Remove('out-file:width')
}
}
DemoDefaultOutFileWidth
Formoreinformationabout$PSDefaultParameterValues,see
about_Preference_Variables.
Parameters
-Append
Addstheoutputtotheendofanexistingfile.
Type:SwitchParameter
Position:Named
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-Confirm
Promptsyouforconfirmationbeforerunningthecmdlet.
Type:SwitchParameter
Aliases:cf
Position:Named
Defaultvalue:False
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-Encoding
Specifiesthetypeofencodingforthetargetfile.Thedefaultvalueisutf8NoBOM.
Theacceptablevaluesforthisparameterareasfollows:
ascii:UsestheencodingfortheASCII(7-bit)characterset.
bigendianunicode:EncodesinUTF-16formatusingthebig-endianbyteorder.
bigendianutf32:EncodesinUTF-32formatusingthebig-endianbyteorder.
oem:UsesthedefaultencodingforMS-DOSandconsoleprograms.
unicode:EncodesinUTF-16formatusingthelittle-endianbyteorder.
utf7:EncodesinUTF-7format.
utf8:EncodesinUTF-8format.
utf8BOM:EncodesinUTF-8formatwithByteOrderMark(BOM)
utf8NoBOM:EncodesinUTF-8formatwithoutByteOrderMark(BOM)
utf32:EncodesinUTF-32format.
BeginningwithPowerShell6.2,theEncodingparameteralsoallowsnumericIDsofregisteredcode
pages(like-Encoding1251)orstringnamesofregisteredcodepages(like
-Encoding"windows-1251").Formoreinformation,seethe.NETdocumentationfor
Encoding.CodePage.
Note
UTF-7*isnolongerrecommendedtouse.AsofPowerShell7.1,awarningiswrittenifyou
specifyutf7fortheEncodingparameter.
Type:Encoding
Acceptedvalues:ASCII,BigEndianUnicode,BigEndianUTF32,OEM,Unicode,UTF7,UTF8,UTF8BOM,UTF8NoBOM,UTF32
Position:1
Defaultvalue:UTF8NoBOM
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-FilePath
Specifiesthepathtotheoutputfile.
Type:String
Aliases:Path
Position:0
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-Force
Overridestheread-onlyattributeandoverwritesanexistingread-onlyfile.TheForceparameter
doesnotoverridesecurityrestrictions.
Type:SwitchParameter
Position:Named
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-InputObject
Specifiestheobjectstobewrittentothefile.Enteravariablethatcontainstheobjectsortype
acommandorexpressionthatgetstheobjects.
Type:PSObject
Position:Named
Defaultvalue:None
Acceptpipelineinput:True
Acceptwildcardcharacters:False
-LiteralPath
Specifiesthepathtotheoutputfile.TheLiteralPathparameterisusedexactlyasitistyped.
Wildcardcharactersarenotaccepted.Ifthepathincludesescapecharacters,encloseitinsingle
quotationmarks.SinglequotationmarkstellPowerShellnottointerpretanycharactersasescape
sequences.Formoreinformation,seeabout_Quoting_Rules.
Type:String
Aliases:PSPath,LP
Position:Named
Defaultvalue:None
Acceptpipelineinput:True
Acceptwildcardcharacters:False
-NoClobber
NoClobberpreventsanexistingfilefrombeingoverwrittenanddisplaysamessagethatthefile
alreadyexists.Bydefault,ifafileexistsinthespecifiedpath,Out-Fileoverwritesthefile
withoutwarning.
Type:SwitchParameter
Aliases:NoOverwrite
Position:Named
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-NoNewline
Specifiesthatthecontentwrittentothefiledoesnotendwithanewlinecharacter.Thestring
representationsoftheinputobjectsareconcatenatedtoformtheoutput.Nospacesornewlinesare
insertedbetweentheoutputstrings.Nonewlineisaddedafterthelastoutputstring.
Type:SwitchParameter
Position:Named
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-WhatIf
Showswhatwouldhappenifthecmdletruns.Thecmdletisnotrun.
Type:SwitchParameter
Aliases:wi
Position:Named
Defaultvalue:False
Acceptpipelineinput:False
Acceptwildcardcharacters:False
-Width
Specifiesthenumberofcharactersineachlineofoutput.Anyadditionalcharactersaretruncated,
notwrapped.Ifthisparameterisnotused,thewidthisdeterminedbythecharacteristicsofthe
host.ThedefaultforthePowerShellconsoleis80characters.Ifyouwanttocontrolthewidthfor
allinvocationsofOut-Fileaswellastheredirectionoperators(>and>>),set
$PSDefaultParameterValues['out-file:width']=2000beforeusingOut-File.
Type:Int32
Position:Named
Defaultvalue:None
Acceptpipelineinput:False
Acceptwildcardcharacters:False
Inputs
PSObject
YoucanpipeanyobjecttoOut-File.
Outputs
None
Out-Filedoesnotgenerateanyoutput.
Notes
Inputobjectsareautomaticallyformattedastheywouldbeintheterminal,butyoucanusea
Format-*cmdlettoexplicitlycontroltheformattingoftheoutputtothefile.Forexample,
Get-Date|Format-List|Out-Fileout.txt
TosendaPowerShellcommand'soutputtotheOut-Filecmdlet,usethepipeline.Alternatively,you
canstoredatainavariableandusetheInputObjectparametertopassdatatotheOut-File
cmdlet.
Out-Filesavesdatatoafilebutitdoesnotproduceanyoutputobjectstothepipeline.
PowerShell7.2addedtheabilitytocontrolhowANSIescapesequencesarerendered.ANSI-decorated
outputthatispassedtoOut-Filecanbealteredbasedonthesettingofthe
$PSStyle.OutputRenderingproperty.Formoreinformation,see
about_ANSI_Terminals.
RelatedLinks
about_Providers
about_Quoting_Rules
Out-Default
Out-Host
Out-Null
Out-String
Tee-Object
Feedback
Submitandviewfeedbackfor
Thisproduct
Thispage
Viewallpagefeedback
Inthisarticle