PowerShell for Windows Admins

Jul 15 2017   4:46AM GMT

Control split output

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

In this post I’ll show you show to control split output – that is control the number of strings that are returned.

If you use –split with just a delimiter you’ll get a split occurring at every occurrence of the delimiter:

PS> 'SundayJanuary 01 Jan 1 New Years Day First Monday if 1st is Saturday or Sunday' -split ' '
SundayJanuary
 01
 Jan
 1
 New
Years
 Day
 First
 Monday
 if
 1st
 is
 Saturday
 or
 Sunday

But we want the holiday information to be in a single string. Rather than spending effort putting it back together you can control the number of strings that are output:

PS> 'SundayJanuary 01 Jan 1 New Years Day First Monday if 1st is Saturday or Sunday' -split ' ',5
SundayJanuary
 01
 Jan
 1
New Years Day First Monday if 1st is Saturday or Sunday

In this case we’ve said we want 5 strings returned so everything after the 4th split is returned as a single string.

This makes our coding easier and neater

$uri = "http://www.officeholidays.com/countries/united_kingdom/index.php"
 $html = Invoke-WebRequest -Uri $uri
 $holidays = ($html.ParsedHtml.getElementsByTagName("table") | 
 where ClassName -eq 'list-table' | 
 select -ExpandProperty InnerText) -split "`n"

$holidays.Count

$hols = foreach ($holiday in $holidays[1..($holidays.Count -1)]){
 $x = $holiday -split ' ',5
 $y = $x[0] -split "day"
 
 $props = [ordered]@{
 DayOfWeek = "$($y[0])day"
 Day = $x[1]
 Month = $y[1]
 Holiday = $x[4]
 }
 
 New-Object -TypeName PSObject -Property $props
 
 }

$hols | Format-Table -AutoSize -Wrap

When I wrote this:

Office holidays

I said that the string handling was ugly and there must be a better way – I remembered!

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: