Solved

Powershell: Padding a string

Posted on 2013-02-07
9
1,389 Views
Last Modified: 2013-02-11
I'm reading a csv file that has already process a date in the format MMDDYYYY. However, for single-digit months, there is no leading 0. I'd like to "pad" this string so that there's a leading 0.

I know I can do something like this
$file = import-csv c:\temp\myfile.csv

foreach ($line in $file) {
   $date = $line.DATE 
   if($date.Length -lt 8){
       $date = -Join ("0",$date)
    } else {
        # date length is good; do nothing
    }
}

Open in new window


I'm looking for the most efficient way to do this (less code as possible)
Thx
0
Comment
Question by:bndit
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 38865453
simply parse the date instead of checking
length and stuff:
$file = import-csv c:\temp\myfile.csv

foreach ($line in $file) {
$date = $line.DATA
$date = [DateTime]::Parse($date).ToString("MMDDYYYY")

Open in new window

0
 
LVL 2

Author Comment

by:bndit
ID: 38865469
what am I doing wrong? See snapshot attached to see how I'm running it (straight on the shell)

Exception calling "Parse" with "1" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:18
+ [DateTime]::Parse <<<< ($date).ToString("MMDDYYYY")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
date.png
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38865634
sorry for the confusion, parse and parseExact can't deal with single digit month even when explicitly defined:
$date = "6102013"
$date = [DateTime]::ParseExact($date, "Mddyyyy",[System.Globalization.CultureInfo]::CurrentCulture) 

Open in new window


also in several places i found that ppl use similar methods to detect single digits months (or days) and simply pad with 0 to work with DateTime objects.
you can shorten your line by doing this:
$file = import-csv c:\temp\myfile.csv
foreach ($line in $file) {
  [DateTime]$date = @{$true=("0"+$line.DATE);$false=$line.DATE}[$line.DATE.Length -lt 8] 
}                

Open in new window

0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 2

Author Comment

by:bndit
ID: 38865715
This article would make me think I could use the static method ParseExact
http://dusan.kuzmanovic.net/2012/05/07/powershell-parsing-date-and-time/

do you know why it's not working?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38865813
I tested parseExact it wont work with single digit month
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 38866056
How about
foreach ($line in import-csv c:\temp\myfile.csv) {
   $date = $line.DATE.PadLeft(8, '0') 
}

Open in new window

or
import-csv c:\temp\myfile.csv | % { $date = $_.Date.PadLeft(8, '0') }

Open in new window

0
 
LVL 2

Author Comment

by:bndit
ID: 38866295
Thanks for trying, but I think it's going to be really hard to convert dates given to me in this format since a 1-digit month and 1-digit day are used. Padding left would yield incorrect dates where the date is 1-digit (i.e. 1271950 would yield 01271950 but I really want 12071950).
0
 
LVL 70

Assisted Solution

by:Qlemo
Qlemo earned 115 total points
ID: 38866324
It is not only hard, it is impossible. Think of 1112013 - is that  01 11 2013 or 11 01 2013 ? I assumed that just the month is missing the leading zero.
0
 
LVL 17

Accepted Solution

by:
Learnctx earned 115 total points
ID: 38866686
It really sounds like the system/application doing the export needs to be rectified rather than production a script or function to compensate for it. I would really investigate why the output is being done incorrectly into the CSV.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question