This article describes how to output a string to a file in PowerShell.
There is a task: quickly create a file under d:\ and write a sentence "Hello World!" into it.
Facing this task, if we immediately think about the FileStream object, then we are wrong! FileStream is a traditional method in .NET! In PowerShell, we can use the Out-File cmdlet to achieve this effect in one step.
Copy the codeThe code is as follows:
PS C:\Users\spaybow> "Hello World!" | Out-File d:\
PS C:\Users\spaybow> type d:\
Hello World!
Let's explain:
The first command uses the out-file cmdlet, input "Hello World!" as a pipeline parameter and output it to d:\. If you do not care about the writing method, whether the file exists or not, or whether the encoding problem is concerned, then you can output a string to a file directly Out-File <file name>.
The second command uses type to display the contents of the file. type is an alias for Get-Content.
This article introduces so much about PowerShell output strings to files. I hope it will be helpful to you. Thank you!