Get-Content - PowerShell Command - PDQ

文章推薦指數: 80 %
投票人數:10人

UTF8: Encodes in UTF-8 format. ... Therefore, by default, when reading a text file, Get-Content returns a collection of string objects, each of which ends ... PowerShellCommandsGet-Content Get-Content[-Credential][-Delimiter][-Encoding{Unknown|String|Unicode|Byte|BigEndianUnicode|UTF8|UTF7|UTF32|Ascii|Default|Oem|BigEndianUTF32}][-Exclude][-Filter][-Force][-Include]-LiteralPath*[-Raw][-ReadCount][-Stream][-Tail][-TotalCount][-UseTransaction][-Wait][] Get-Content[-Path*][-Credential][-Delimiter][-Encoding{Unknown|String|Unicode|Byte|BigEndianUnicode|UTF8|UTF7|UTF32|Ascii|Default|Oem|BigEndianUTF32}][-Exclude][-Filter][-Force][-Include][-Raw][-ReadCount][-Stream][-Tail][-TotalCount][-UseTransaction][-Wait][] Get-Content[-Delimiter][-Encoding{Unknown|String|Unicode|Byte|BigEndianUnicode|UTF8|UTF7|UTF32|Ascii|Default|Oem}][-Force][-Raw][-Stream][-Wait][-UseTransaction][] TheGet-Contentcmdletgetsthecontentoftheitematthelocationspecifiedbythepath,suchasthetextinafile.Itreadsthecontentonelineatatimeandreturnsacollectionofobjects,eachofwhichrepresentsalineofcontent.BeginninginWindowsPowerShell3.0,thiscmdletcanalsogetaspecifiednumberoflinesfromthebeginningorendofanitem.Infilesystemdrives,youcanusethetheGet-Contentcmdlettogetcontentthatyoudisplayatthecommandline,saveinavariableforprocessing,orwritetoanotherfile.Itisnotvalidonfolders.Note:ThiscustomcmdlethelpfileexplainshowtheGet-Contentcmdletworksinafilesystemdrive.ForinformationabouttheGet-Contentcmdletinalldrives,type"Get-HelpGet-Content-Path$null"orseeGet-Contentathttp://go.microsoft.com/fwlink/?LinkID=113310. Parameters -EncodingDefaultvalueisASCIISpecifiesthefileencoding.ThedefaultisASCII.Validvaluesare:--ASCII:UsestheencodingfortheASCII(7-bit)characterset.--BigEndianUnicode:EncodesinUTF-16formatusingthebig-endianbyteorder.--Byte:Encodesasetofcharactersintoasequenceofbytes.--String:Usestheencodingtypeforastring.--Unicode:EncodesinUTF-16formatusingthelittle-endianbyteorder.--UTF7:EncodesinUTF-7format.--UTF8:EncodesinUTF-8format.--Unknown:Theencodingtypeisunknownorinvalid.Thedatacanbetreatedasbinary.EncodingisadynamicparameterthattheFileSystemprovideraddstotheGet-Contentcmdlet.Thisparameterworksonlyinfilesystemdrives.Whenreadingfromandwritingtobinaryfiles,useavalueofBytefortheEncodingdynamicparameterandavalueof0fortheReadCountparameter.AReadCountvalueof0readstheentirefileinasinglereadoperationandconvertsitintoasingleobject(PSObject).ThedefaultReadCountvalue,1,readsonebyteineachreadoperationandconvertseachbyteintoaseparateobject,whichcauseserrorswhenyouusetheSet-Contentcmdlettowritethebytestoafile. -DelimiterDefaultvalueisEnd-of-linecharacterSpecifiesthedelimiterthatGet-Contentusestodividethefileintoobjectswhileitreads.Thedefaultis"\n",theend-of-linecharacter.Therefore,bydefault,whenreadingatextfile,Get-Contentreturnsacollectionofstringobjects,eachofwhichendswithanend-of-linecharacter.Whenyouenteradelimiterthatdoesnotexistinthefile,Get-Contentreturnstheentirefileasasingle,undelimitedobject.Youcanusethisparametertosplitalargefileintosmallerfilesbyspecifyingafileseparator,suchas"EndofExample",asthedelimiter.Thedelimiterispreserved(notdiscarded)andbecomesthelastitemineachfilesection.DelimiterisadynamicparameterthattheFileSystemprovideraddstotheGet-Contentcmdlet.Thisparameterworksonlyinfilesystemdrives.TroubleshootingNote:Currently,whenthevalueoftheDelimiterparameterisanemptystring,Get-Contentdoesnotreturnanything.Thisisaknownissue.ToforceGet-Contenttoreturntheentirefileasasingle,undelimitedstring,enteravaluethatdoesnotexistinthefile. -Force[]DefaultvalueisFalseGetsthecontentsofallfiles,includinghiddenfiles.Bydefault,Get-Contentdoesnotgetthecontentsofhiddenfilesunlessyouspecifythehiddenfilebyname. -RawIgnoresnewlinecharactersandreturnstheentirecontentsofafileinonestring.Bydefault,thecontentsofafileisreturnedasaarrayofstringsthatisdelimitedbythenewlinecharacter.RawisadynamicparameterthattheFileSystemprovideraddstotheGet-Contentcmdlet.Thisparameterworksonlyinfilesystemdrives.ThisparameterisintroducedinWindowsPowerShell3.0. -Wait[]DefaultvalueisFalseWaitsforthecmdlettogetthecontentbeforereturningthecommandprompt.Whilewaiting,Get-Contentchecksthefileonceeachseconduntilyouinterruptit,suchasbypressingCTRL+C.WaitisadynamicparameterthattheFileSystemprovideraddstotheGet-Contentcmdlet.Thisparameterworksonlyinfilesystemdrives. -StreamGetsthecontentsofthespecifiedalternateNTFSfilestreamfromthefile.Enterthestreamname.Wildcardsarenotsupported.StreamisadynamicparameterthattheFileSystemprovideraddstotheGet-Contentcmdlet.Thisparameterworksonlyinfilesystemdrives.ThisparameterisintroducedinWindowsPowerShell3.0. -UseTransaction[]Includesthecommandintheactivetransaction.Thisparameterisvalidonlywhenatransactionisinprogress. -CredentialDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifiesauseraccountthathaspermissiontoperformthisaction.Thedefaultisthecurrentuser.Typeausername,suchasUser01orDomain01\User01,orenteraPSCredentialobject,suchasonegeneratedbytheGet-Credentialcmdlet.Ifyoutypeausername,youwillbepromptedforapassword.ThisparameterisnotsupportedbyanyprovidersthatareinstalledwithWindowsPowerShell. -ExcludeDefaultvalueisNoneAcceptspipelineinputFalseSpecifies,asastringarray,theitemoritemsthatthiscmdletomitswhenperformingtheoperation.ThevalueofthisparameterqualifiesthePathparameter.Enterapathelementorpattern,suchas*.txt.Wildcardsarepermitted. -FilterDefaultvalueisNoneAcceptspipelineinputFalseSpecifiesafilterintheprovider'sformatorlanguage.ThevalueofthisparameterqualifiesthePathparameter.Thesyntaxofthefilter,includingtheuseofwildcards,dependsontheprovider.Filtersaremoreefficientthanotherparameters,becausetheproviderappliesthemwhenthiscmdletgetstheobjects,ratherthanhavingWindowsPowerShellfiltertheobjectsaftertheyareretrieved. -IncludeDefaultvalueisNoneAcceptspipelineinputFalseSpecifies,asastringarray,theitemoritemsthatthiscmdletincludesintheoperation.ThevalueofthisparameterqualifiesthePathparameter.Enterapathelementorpattern,suchas*.txt.Wildcardsarepermitted. -LiteralPathThisvalueisrequiredDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifiesthepathtoanitem.UnlikethePathparameter,thevalueofLiteralPathisusedexactlyasitistyped.Nocharactersareinterpretedaswildcards.Ifthepathincludesescapecharacters,encloseitinsinglequotationmarks.SinglequotationmarkstellWindowsPowerShellnottointerpretanycharactersasescapesequences. -PathThisvalueisrequiredDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifiesthepathtoanitem.Get-Contentgetsthecontentoftheitem.Wildcardsarepermitted. -ReadCountDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifieshowmanylinesofcontentaresentthroughthepipelineatatime.Thedefaultvalueis1.Avalueof0(zero)sendsallofthecontentatonetime.Thisparameterdoesnotchangethecontentdisplayed,butitdoesaffectthetimeittakestodisplaythecontent.AsthevalueofReadCountincreases,thetimeittakestoreturnthefirstlineincreases,butthetotaltimefortheoperationdecreases.Thiscanmakeaperceptibledifferenceinverylargeitems. -TailDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifiesthenumberoflinesfromtheendofafileorotheritem.ThisparameterwasintroducedinWindowsPowerShell3.0.YoucanusetheTailparameternameoritsalias,Last. -TotalCountDefaultvalueisNoneAcceptspipelineinputByPropertyNameSpecifiesthenumberoflinesfromthebeginningofafileorotheritem.Thedefaultis-1(alllines).YoucanusetheTotalCountparameternameoritsaliases,FirstorHead. Thiscmdletsupportsthecommonparameters:Verbose,Debug,ErrorAction,ErrorVariable,WarningAction,WarningVariable,OutBuffer,PipelineVariable,andOutVariable. Inputs System.Int64,System.String[],System.Management.Automation.PSCredential Youcanpipethereadcount,totalcount,paths,orcredentialstoGet-Content.Outputs System.Object,System.String Get-Contentreturnsobjectsthatrepresentthecontentthatitgets.Theobjecttypedependsonthecontenttype.IfyouusetheStreamparameter,thecmdletreturnsthealternatedatastreamcontentsasastring. Examples ThiscommandgetsthecontentoftheChapter1.txtfileanddisplaysitintheconsole:C:\PS>Get-Content-PathC:\Chapters\chapter1.txt ItusesthePathparametertospecifythenameoftheitem.Get-Contentactuallypassesthecontentdownthepipeline,butbecausetherearenoothercmdletsinthepipeline,WindowsPowerShellformatsthecontentsanddisplaysitintheconsole.Thiscommandgetsthefirst50linesoftheLog060912.txtfileandstorestheminthesample.txtfile:C:\PS>Get-ContentC:\Logs\Log060912.txt-TotalCount50|Set-ContentSample.txt ThecommandusestheGet-Contentcmdlettogetthetextinthefile.(ThenameofPathparameter,whichisoptional,isomitted.)TheTotalCountparameterlimitstheretrievaltothefirst50lines.Thepipelineoperator(|)sendstheresulttoSet-Content,whichplacesitinthesample.txtfile.ThiscommandgetsthefifthlineoftheCmdlets.txttextfile:C:\PS>(Get-ContentCmdlets.txt-TotalCount5)[-1] ItusestheTotalCountparametertogetthefirstfivelinesandthenusesarraynotationtogetthelastline(indicatedby"-1")oftheresultingset.ThiscommandgetsthecontentsofallCSVfilesintheDataSetssubdirectory:C:\PS>Get-Content.\DataSets\*.csv-Delimiter"*---*"-Force-EncodingUTF8 ItusestheForceparametertogetallfiles,includinghiddenfiles,andtheEncodingparametertospecifythefileencoding.ThecommandalsousestheDelimiterparametertodividethereturnedcontentintosets,eachofwhichendsattheCSVfilerowthatcontainsthe"*----*"marker.ThiscommandusestheStreamparametertogetthecontentoftheZone.Identifieralternatedatastream:C:\PS>Get-Content.\Copy-Scripts.ps1-StreamZone.Identifier [ZoneTransfer] ZoneId=3TheoutputincludesZoneIDvalueof3,whichrepresentstheInternet.TheStreamparameterisintroducedinWindowsPowerShell3.0.Thecommandsinthisexamplegetthecontentsofamodulemanifestfile(.psd1)asahashtable:C:\PS>$Manifest=(Get-Module-ListPSScheduledJob).Path C:\PS>$Hash=Invoke-Expression(Get-Content$Manifest-Raw) C:\PS>$Hash NameValue --------- CopyrightcMicrosoftCorporation.Allrightsreserved. ModuleToProcessMicrosoft.PowerShell.ScheduledJob.dll FormatsToProcessPSScheduledJob.Format.ps1xml PowerShellVersion3.0 CompanyNameMicrosoftCorporation GUID50cdb55f-5ab7-489f-9e94-4ec21ff51e59 AuthorMicrosoftCorporation CLRVersion4.0 CmdletsToExport{New-JobTrigger,Add-JobTrigger,Remove-JobTrigger,Get-JobTrigger...} TypesToProcessPSScheduledJob.types.ps1xml HelpInfoURIhttp://go.microsoft.com/fwlink/?LinkID=223911 ModuleVersion1.0.0.0 C:\PS>$Hash.ModuleToProcess Microsoft.PowerShell.ScheduledJob.dll Themanifestfilecontainsahashtable,butifyougetthecontentswithouttheRawdynamicparameter,itisreturnedasanarrayofnewline-delimitedstrings.TheRawdynamicparameterisintroducedinWindowsPowerShell3.0.ThefirstcommandusesthePathpropertyofmodulestogetthepathtothefilethatcontainsthemodulemanifestforthePSScheduledJobmodule.Itsavesthepathinthe$Manifestvariable.ThesecondcommandusestheInvoke-ExpressioncmdlettorunaGet-ContentcommandandtheRawdynamicparameteroftheGet-Contentcmdlettogetthecontentsofthemodulemanifestfileinasinglestring.Thecommandsavesthehashtableinthe$Hashvariable.ThethirdcommandgetsthehashtableintheHashvariable.Thecontentsisreturnedasacollectionofname-valuepairs.ThefourthcommandusestheModuleToProcesspropertyofthehashtabletogetthevalueoftheModuleToProcesskeyinthemodulemanifest.ThisexampleshowshowtousetheReadCountparameteroftheGet-Contentcmdletwithavalueof0toavoidbyte-relatederrorswhenusingtheSet-Contentcmdlettowritethebytestoafile:C:\PS>$a=Get-Content-Path.\Download.zip-EncodingByte-ReadCount0 Set-Content-Path\\Server\Share\Download.zip-EncodingByte-Value$a $b=Get-Content-Path.\Download.zip-EncodingByte Set-Content-Path\\Server\Share\Download.zip-EncodingByte-Value$b Set-Content:Cannotproceedwithbyteencoding.Whenusingbyteencodingthecontentmustbeoftypebyte. Atline:1char:1 +Set-Content\\Server\Share\Download.zip-EncodingByte-Value$b +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CategoryInfo:InvalidArgument:(:)[Set-Content],PSArgumentException +FullyQualifiedErrorId:Argument,Microsoft.PowerShell.Commands.SetContentCommandWhengettingthecontentofafileinbytes,Get-Contentcreatesanobject(PSObject)forthebytesineachreadoperation.Ifyoureadthebytesoneatatime,whichisthedefault,Get-Contentcreatesanobjectforeachbyte.TheobjectscauseerrorswhenyouusetheSet-Contentcmdlettowritethebytestoafile.ThefirstcommandusestheGet-ContentcmdlettogetthecontentsoftheDownload.zipfileandsaveitinthe$avariable.ThecommandusestheEncodingdynamicparameterwithavalueofByte.ItalsousestheReadCountparameterwithavalueof0,whichdirectsGet-Contenttogetthefilecontentsinasinglereadoperation.ThedefaultvalueoftheReadCountparameter,1,getsonebyteatatime.ThesecondcommandusestheSet-Contentcmdlettowritethebytesinthe$avariabletotheDownload.zipfileonafileshare.Thecommandsucceeds.ThethirdandfourthcommandsshowthesamesequencewithouttheReadCountparameter.ThethirdcommandusestheEncodingdynamicparameteroftheGet-ContentcmdlettogetthecontentsoftheDownload.zipfileandsaveitinthe$bvariable.BecausethecommandomitstheReadCountparameter,itusesthedefaultvalueof1.ThefourthcommandusestheSet-Contentcmdlettowritethebytesinthe$bvariabletotheDownload.zipfileonafileshare.Becausethecontentisacollectionofobjects,ratherthanasingleobjectthatcontainsabytearray,thecommandfails. AdditionalNotes*Thiscmdletisdesignedtoworkwiththedataexposedbyanyprovider.Togettheprovidersinyoursession, usetheGet-PSProvidercmdlet.Formoreinformation,see about_Providers(http://go.microsoft.com/fwlink/?LinkID=113250). * ThisworkislicensedunderaCreativeCommonsAttribution4.0International.ItisattributedtoMicrosoftCorporationandcanbefoundhere.PowerShellCommands



請為這篇文章評分?