Removing Unwanted Characters

21 06 2010

Suppose you have a variable and you want to remove all unwanted characters from it – for example commas.

In PowerShell, this is as easy as:

PS C:\> 'a,,b,c,d,' -replace ','

To remove multiple unwanted characters, simply chain more -replace operators on the end (note that some characters must be escaped, as we are using a regex the escape character is a backslash):

PS C:\> '.a,a\b,b\c,b\d\,d.\' -replace ',' -replace '\\' -replace '\.'

Converting from UNIX time to a PoSh DateTime object

2 04 2010

Suppose you have a log file from a UNIX/Linux (or some derivative) system which has timestamps in UNIX time format and you want to convert them to shiny DateTime objects. Here’s an example of how to do that, wrapped in a PowerShell function for convenience:

Function get-Unixdate ($UnixDate) {

It returns a PowerShell DateTime object, so can then be manipulated using the standard DateTime methods, eg

PS> $logtime = Get-UnixDate 1269313872.893866062
PS> $logtime

Tuesday, 23 March 2010 4:11:12 p.m.

PS> $logtime.IsDaylightSavingTime()
PS> $logtime.dayofweek
PS> $logtime.minute
PS> $logtime.tostring("g")
23/03/2010 4:11 p.m.
PS> $logtime.DayOfYear
PS> $logtime.AddDays(-30)

Sunday, 21 February 2010 4:11:12 p.m.

PS> ($logtime.adddays(14)).isdaylightsavingtime()


I have added the function to my profile, it comes in useful quite often.

Here’s some tips on working with PowerShell DateTime objects and the MSDN documentation on formatting DateTime output