How to make your submissions look good in the Scripting Games site's File window.

In the course of participating in the practice event, and working on event 1, I've noticed a couple of things about the way files are displayed in the File window on the Scripting Games site:

  • The site treats all files as ASCII; when you upload a Unicode file, syntax highlighting doesn't work and you wind up with what looks like an extra blank line between every line of the original file.
  • Transcripts taken with PowerShell's Start-Transcript command frequently contain lone Carriage Return or Line Feed characters, whereas the Scripting Games site appears to only like the CRLF pair. For example, lines that are separated by only LF (such as those in PowerShell's error or warning output), appear as a single line in the File window of the Games site.

I've written a function to clean up the encoding and content of files before uploading them to the Games site. It takes advantage of the fact that Get-Content has no problem reading files with any combination of EOL characters, and that Set-Content always injects CRLF pairs between its input strings. It also searches the file for any multi-byte Unicode characters; if none were found, it converts the file encoding to ASCII for a nicer display on the Games site.

#requires -Version 3.0

function Convert-GamesFile
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateScript({ Test-Path -Path $_ -PathType Leaf })]
        [string]
        $Path,

        [switch]
        $BackupOriginal
    )

    $contents = Get-Content -LiteralPath $Path -ErrorAction Stop

    # Check for Unicode characters

    $encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::Ascii

    foreach ($line in $contents)
    {
        if ([System.Text.Encoding]::UTF8.GetByteCount($line) -ne $line.Length)
        {
            Write-Warning "File '$Path' contains multi-byte characters."
            Write-Warning "File encoding will be Unicode, though this doesn't display as well on the Scripting Games site."
            
            $encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::Unicode
            break
        }
    }

    # Perform updates

    if ($BackupOriginal)
    {
        Copy-Item -LiteralPath $Path -Destination ("$Path.bak") -ErrorAction Stop
    }

    $contents | Set-Content -LiteralPath $Path -Encoding $encoding -ErrorAction Stop
}
Posted in:
About the Author

Dave Wyatt

Dave Wyatt is a Microsoft MVP (PowerShell) and a member of PowerShell.org's Board of Directors.