PowerTip: Create an ASCII File from Inside PowerShell

PowerTip: Create an ASCII File from Inside PowerShell

  • Comments 3
  • Likes

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

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Hi Ed,

    PS II> # or maybe:

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

    PS II> # but untested

  • @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

  • 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:\fso\myproc.txt", (gps), [Text.Encoding]::ASCII)

    But this is no easier than using Powershell native cmdlets!

    Klaus