PowerTip: Create an ASCII File from Inside PowerShell

Summary: Learn how to create an ASCII file from inside Windows PowerShell.

Hey, Scripting Guy! Question I want to create an ASCII text file to hold the results of the Get-Process cmdlet. How can this be done?

               Hey, Scripting Guy! Answer

a. Pipe the results to the Out-File cmdlet and use the -encoding parameter to specify ASCII:

GPS | Out-File -FilePath c:\fso\myproc.txt -Encoding ascii

b. Use the InputObject parameter of the Out-File cmdlet and use the –encoding parameter to specify ASCII:

Out-File -InputObject (gps) -FilePath c:\fso\myproc.txt -Encoding ascii

c. Use redirection like this:

Get-Process >>c:\fso\myprocess.txt

Comments (3)

  1. Walid Toumi says:

    Hi Ed,

    PS II> # or maybe:

    PS II> $OutputEncoding = [System.Text.Encoding]::ASCII

    PS II> # but untested

  2. Ed Wilson says:

    @Walid Toumi , this is a great idea. Here is how to use .NET Framework classes to do an explicit conversion to ASCII. Keep in mind, that a more robust example would use Try / Catch / Finally and specify a fall back encoding in case that a character could NOT encode as ASCII. Here is the code.

    PS C:> $encoding = [system.text.encoding]::GetEncoding("ascii")

    PS C:> $string = "This is a string"

    PS C:> [byte[]]$bytes = $encoding.GetBytes($string)

    PS C:> $asciiString = $encoding.GetString($bytes)

    PS C:> $asciiString

    This is a string

  3. Klaus Schulte says:

    If you really want to use the .Net classes to write to a file with some special encoding, you can do it that way

    [IO.File]::WriteAllText("c:fsomyproc.txt", (gps), [Text.Encoding]::ASCII)

    But this is no easier than using Powershell native cmdlets!


Skip to main content