Set-Content - PowerShell - SS64.com
文章推薦指數: 80 %
Write or replace the content in an item. This will overwrite any pre-existing content. ... Under Windows, Set-Content will create ANSI files by default. SS64 PowerShell How-to Set-Content Writeorreplacethecontentinanitem.Thiswilloverwriteanypre-existingcontent. Syntax Set-Content[-path]string[] [-value]Object[][-includestring[]][-excludestring[]] [-filterstring][-NoNewline][-EncodingCharSet] [-passThru][-force][-Streamstring][-credentialPSCredential] [-whatIf][-confirm][-UseTransaction][CommonParameters] Set-Content-literalPathstring[] [-value]Object[][-includestring[]][-excludestring[]] [-filterstring][-NoNewline][-EncodingCharSet] [-passThru][-force][-Streamstring][-credentialPSCredential] [-whatIf][-confirm][-UseTransaction][CommonParameters] Set-Content[-Streamstring][-EncodingCharSet][-Force] [-Confirm][-WhatIf][-UseTransaction][CommonParameters] Key -Pathstring Thepathtotheitemthatwillreceivethecontent. Wildcardsarepermitted. -LiteralPathstring LikePathabove,onlythevalueisusedexactlyastyped. Nocharactersareinterpretedaswildcards.Ifthepathincludesany escapecharactersthenenclosethepathinsinglequotationmarks. -EncodingCharSet[DynamicParameter(FileSystemOnly)] Encodeinaspecificcharacterset: UnknownUnknownorinvalid.Thedatacanbetreatedasbinary. StringUsetheencodingtypeforastring. UnicodeUTF-16formatlittle-endianbyteorder. ByteEncodecharactersasasequenceofbytes. BigEndianUnicodeUTF-16formatbig-endianbyteorder. UTF8UTF-8format. UTF7UTF-7format. UTF32UTF-32format. UTF8BOMUTF-8formatwithByteOrderMark(BOM)*PS6.0+ UTF8NOBOMUTF-8formatwithoutByteOrderMark(BOM)*PS6.0+ ASCIIASCII(7-bit)characterset. DefaultThesystem'sactiveANSIcodepage*PS3.0+ OemUsethedefaultencodingforMS-DOSandconsoleprograms,normallyANSI.*PS3.0+ BigEndianUTF32UTF-32BigEndian*PS3.0toPS5.1 Thedefaultencodingis'Default'thesystem'sactiveANSIcodepage. -ValueObject Thenewcontentfortheitem. -Excludestring Omitthespecifieditems,thisqualifiesthe-Pathparameter. Wildcardsarepermitted.e.g."*.log" -Includestring ChangeonlythespecifieditemsinthePath. Wildcardsarepermitted.e.g."*.txt" -Filterstring Afilterintheprovider'sformatorlanguage. Theexactsyntaxofthefilter(wildcardsupportetc)dependsontheprovider. Filtersaremoreefficientthan-include/-exclude,becausetheprovider appliesthefilterwhenretrievingtheobjects,ratherthanhaving PowerShellfiltertheobjectsaftertheyareretrieved. -NoNewline Indicatesthatthiscmdletusesthenonewlinesetting. -PassThru PasstheobjectcreatedbySet-Contentthroughthepipeline. -Force Overriderestrictionsthatpreventthecommandfromsucceeding.Forcewillreplace thecontentsofafile,evenifthefileisread-only,butwillnotoverride securitypermissions.Withoutthisparameter,read-onlyfilesarenotchanged. -Streamstring Createsorreplacesthecontentinthespecifiedalternatedatastream.Ifthe streamdoesnotyetexist,Set-Contentcreatesit. Enterthestreamname.Wildcardsarenotsupported. StreamisadynamicparameterthattheFileSystemprovideraddstotheSet-Contentcmdlet. Thisparameterworksonlyinfilesystemdrives. YoucanusetheSet-ContentcmdlettochangethecontentoftheZone.Identifieralternatedatastream. However,itisnottherecommendedwaytoeliminatesecuritychecksthatblockfiles thataredownloadedfromtheInternet.Ifyouverifythatadownloadedfileissafe, usetheUnblock-Filecmdlet. ThisparameterisintroducedinPowerShell3.0. -CredentialPSCredential Presentauser/passwordcredentialtovalidateaccesstothefile. ThisisnotyetsupportedbyanyprovidersinstalledwithWindowsPowerShell. -WhatIf Describewhatwouldhappenifyouexecutedthecommandwithoutactually executingthecommand. -Confirm Promptforconfirmationbeforeexecutingthecommand. -UseTransaction Includethecommandintheactivetransaction. Set-Contentisastring-processingcmdletthatwritesnewcontentorreplacesthecontentinafile.Set-ContentwillreplacetheexistingcontentanddiffersfromtheAdd-Contentcmdletwhichwillappendcontenttoafile. TosendcontenttoSet-Contentyoucanusethe-valueparameteronthecommandlineorsendcontentthroughthepipeline. UnderWindows,Set-ContentwillcreateANSIfilesbydefault. Thiscanbeconfiguredviathe$PSDefaultParameterValuespreferencevariable. set-content-encodingUTF8willwriteaBOMifoneisavailableinthesourcefile,orifthesourcehasbeenexplicitlyconvertedtoUTF8(Get-Content-EncodingUTF8). UnderPowerShellCoreedition,theencodingdefaultstoBOM-lessUTF-8. AnalternativeistouseOut-Fileor>whichdefaulttoUTF-16LE. StandardAliasesforSet-Content:sc Examples Writeastringintoatextfile: PSC:\>Set-content-pathC:\test.txt-value"HelloWorld" WritethecurrentdateintoaCSVfile: PSC:\>get-date|set-contentC:\Test_date.csv ChangetheformatofafilefromASCIItoUTF8: $filename="c:\docs\demo.csv" (Get-Content$filename)|Set-Content$filename-EncodingUTF8 ChangetheformatofafilefromASCII(noBOM)toUTF8(withBOM): $filename="c:\docs\demo.csv" (Get-Content$filename-EncodingUTF8)|Set-Content$filename-EncodingUTF8 FindandReplacesometextineverylineofthefilefoo.txt Inthiscommand,theparenthesesaround(Get-Content)ensurethattheGetoperationiscompletedbeforetheSetoperationbegins,wthoutthisthetwofunctionswouldbothtrytoaccessthefileatthesametime: PSC:\>(get-contentfoo.txt)|foreach-object{$_-replace"oldTxt","newTxt"}|set-contentfoo.txt Readthecontentofthefilesource.txtandsaveitintodestination.txtencodingthefileasUTF8:Get-Contentsource.txt|Set-Contentdestination.txt-EncodingUTF8 “Amanshouldhearalittlemusic,readalittlepoetry,andseea finepictureeverydayofhislife,inorderthatworldlycaresmay notobliteratethesenseofthebeautifulwhichGodhasimplantedin thehumansoul”~Goethe RelatedPowerShellCmdlets: Add-Content-Addtothecontentoftheitem. Get-Content-Getthecontentoftheitematthespecifiedlocation. Clear-Content-Removecontentfromafile/item. Copy-Item-Copyanitemfromonelocationtoanotherwithinanamespace. Set-Item-Changethevalueofanitem. get-help-about_namespace. Copyright©1999-2022SS64.com Somerightsreserved
延伸文章資訊
- 1PowerShell 輸出結果編碼問題 - 黑暗執行緒
Do-Something.ps1 > output.txt 存檔是用ANSI/BIG5 編碼,但事實不然。 ... 其編碼Export-PSSession 用UTF8(含BOM) New-Ite...
- 2How to convert multiple files encoded in UTF-8-BOM to ANSI?
I would like the output to be correct in both cases. If Powershell it's not the solution, what el...
- 3Set-Content - PowerShell - SS64.com
Write or replace the content in an item. This will overwrite any pre-existing content. ... Under ...
- 4Out-File -encoding problems - TechNet - Microsoft
I have written one of my first PowerShell scripts to execute after I mirror my ... other than to ...
- 5Thomson Data Analyzer - Save as ANSI Workaround (TDAv3.01)