Gene
Gene

Reputation: 9

Powershell pattern matching

I have a requirement to create directories based on a numeric 9 digit with leading zeros primary key from an order entry database on a remote server.
Each morning a new directory should be created. The directory name will be the primary key number of the new customer. I already have the sql statement extracting the primary key information into a text file using BCP that preserves the leading zeros.
This file is transferred from the database server to the local directory where the folders need to be created. Using some PowerShell code that I think I found I am trying to create the folders from the text file that I have been modifying.
I need the leading zeros preserved in the folder name so I can reference back to the database later in the project. My problem is that when I run the PowerShell script, no folders are created. I think I have the problem isolated to the pattern definition, but don't understand what is wrong.

Input txt file example

001132884
001454596
001454602
001454605
001454606
001454601
001107119
001454600
001454608

PowerShell script

$folder="Customerdocuments";   # Directory to place the new folders in.
$txtFile="E:\dirtext.txt";     # File with list of new folder-names
$pattern="\d+.+";              # Pattern that lines must match      


Get-Content $txtFile | %{

    if($_ -match $pattern)
    {
        mkdir "$folder\$_";
    }
}

Upvotes: 0

Views: 868

Answers (1)

user6811411
user6811411

Reputation:

  • I'm missing a clear question/error report.
  • Your pattern takes all digits (greedy) from input \d+
    and requires at least one other (any) character .+ which isn't present in your sample file.
  • So your issue isn't related to leading zeroes.
  • Better specify exactly 9 digits and put that into a Where-object,
  • The path from $folder will be relative to the current folder and should be build using Join-Path
  • As mkdir is just a wrapper function for New-Item and it supports piped input I'd use it directly.
$folder="Customerdocuments";   # Directory to place the new folders in.
$txtFile="E:\dirtext.txt";     # File with list of new folder-names
$pattern="^\d{9}$"             # Pattern that lines must match      

Get-Content $txtFile | Where-Object {$_ -match $pattern}|
    New-Item -Path {Join-Path $folder $_} -ItemType Directory | Out-Null
}

Upvotes: 1

Related Questions