One task that seems to crop up fairly frequently is that two variables need to exchange their values. I’ve recently had this issue. I have been looking at a list of mailboxes and one of the questions was when were these mailboxes last accessed. The data is in CSV format so the date information is held as a string - “10/06/2009” – 10th June 2009 in UK format. When try to turn that into a date we can use for comparisons we get
PS> [datetime]"10/6/09"
06 October 2009 00:00:00
Oops. Not quite what we wanted. With PowerShell we have to input the string as “mm/dd/yy” ie in US format. So we need to swap the month and the day around.
In a lot of programming languages we would need to use a third variable as a temporary step
PS> $a=1
PS> $b=2
PS> $a;$b
1
2
PS> $t=$a
PS> $a=$b
PS> $b=$t
PS> $a;$b
2
1
We can make this a good bit shorter
PS> $a=1
PS> $b=2
PS> $a;$b
1
2
PS> $a,$b = $b,$a
PS> $a;$b
2
1
So we make the swap in one line and don’t need the temporary step.
This means I can get my date
PS> $s = "10/06/2009"
PS> $d = $s -split "/"
PS> $d[0],$d[1] = $d[1],$d[0]
PS> [datetime]($d -join "/")
10 June 2009 00:00:00
Plus the –split and –join operators in PowerShell v2 make this easier
Technorati Tags:
PowerShell,
v2