- Settings:
Page
Normal
Plain layout without fancy styles
Font
Normal
Large fonts
Very large fonts
Colour
Normal
Restful colour scheme
Light text on a dark background

Note: user account creation on this site has been disabled.

Programming, speculative fiction, science, technology
Powered by Drupal, an open source content management system
Scope
Include Children
If you select a term with children (sub-terms), do you want those child terms automatically included in the search? This requires that "Items containing" be "any."
Categories

Everything in the Events vocabulary

"Events" is used for: Convention Post, Page, Story.

People mentioned in the articles

"People" is used for: Page, Convention Post, Story.

Themes mentioned in the article

"Themes" is used for: Page, Convention Post, Story.
Skip to top of page

A script to reverse a file in Powershell

I was baffled to discover that it's actually not at all easy to reverse the rows of a spreadsheet in Excel. Extensive Googling lead me to some advanced commands where you really had to Know What You're Doing. Since I don't usually Know What I'm Doing in Excel, I wrote a Powershell script to do the same thing. Actually, this script takes any file, reverses it, and writes it to a different file.

Body:

The "meat" of this script is just one statement:

[array]::Reverse($rows)

But first we need to read the file and generate an output file name, unless it is provided by the user.

Here is the whole script.

# The first parameter, fileName, is mandatory. It's the file we want to reverse.
# The second parameter, outputFileName, is optional. If you don't provide it, the script will generate
# an output file name for you.

param(
#Application Name - Required
[parameter(Mandatory = $true)]
[string]$fileName,

[string]$outputFileName
)

# Read the content of $fileName all at once

$rows = Get-Content $fileName

# If the output file name is not provided, generate it by appending "Rev" to the $fileName, before the extension.
# The code separates $fileName into directory name, file name, and extension, calling the appropriate methods
# of .NET class System.IO.Path, and then assembles $outputFileName from those pieces, with "Rev" inserted.

if (!$outputFileName) {
$outputFileName = [System.IO.Path]::GetDirectoryName($fileName) + '\' + [System.IO.Path]::GetFileNameWithoutExtension($fileName) + "Rev." + [System.IO.Path]::GetExtension($fileName)
}

# Reverse array contents and then output it again:
[array]::Reverse($rows)

# $rows is piped to out-file, which writes the $rows array all at once
# to file named $outputFileName, with UTF8 encoding. (The default encoding
# is something else, and the output file would be human-unreadable if you don't specify encoding.)

$rows | out-file $outputFileName -encoding UTF8