0

I have a powershell script that goes into a files, and for every instance of E:, it will replace it with CBM-FS01|2013-02-03|E:

$filenames = @("C:\SCRIPT\CBM-FS01-E-20130203114114.txt.out")
foreach ($file in $filenames) {
    $outfile = "$file" + ".sql"

    Get-Content $file | Foreach-object {
       $_ -replace "E:","CBM-FS01|2013-02-03|E:" `
    } | Set-Content $outfile
}

If you look close, you can see that I'm getting this information based on the file name. The file name will always be MNEMONIC-MACHINE-DRIVE-YYYMMDDHHMMSS.txt.

Modifying the script for a few files is fine, but I could potentially need to run this on a hundred files! Is there a way using powershell to use the GET-CHILDITEM cmdlet and have powershell automatically perform the -replace based on the different file names?

EDIT: I need to extract parts of the file name, and insert it into the file. For example, for a file CBM-FS01-E-20130203114114.txt, I need to extract the mnemonic-machine (CBM-FS01) and the YYYMMDD (2013-02-03) into the file. Hence

$_ -replace "E:","CBM-FS01|2013-02-03|E:" `

2 Answers 2

1

I think this should work, provided those file name patterns are predictable (and I've predicted them correctly)

$filenames = @("C:\SCRIPT\CBM-FS01-E-20130203114114.txt.out")

$regex = '^([^-]+-[^-]+)-([A-Z])-(\d{4})(\d\d)(\d\d).+'

foreach ($file in $filenames) {

    $outfile = "$file" + ".sql"

    $ReplaceString = ($file | Split-Path -leaf) -replace $regex,'$1|$3-$4-$5|$2:'

    Get-Content $file | Foreach-object {
       $_ -replace "E:",$ReplaceString
    } | Set-Content $outfile
}
2
  • That works! BUT, we have a few oddballs were the file name is CBM-EXXFS-001-E-20130203114114.txt and CBMFS01-E-20130203114114.txt. How would I modify the regex? Commented Mar 19, 2013 at 20:15
  • Disregard. I did a little experimenting. For the first example, I modified it to $regex = '^([^-]+-[^-]+-[^-]+)-([A-Z])-(\d{4})(\d\d)(\d\d).+' Commented Mar 19, 2013 at 20:29
0

Not too sure of the question. It sounds like you have a whole pile of files with the same pattern. You can use the -match operator to do some regex comparison.

$pattern = '[a-zA-Z]+-[a-zA-Z]+-E-[0-9]+\.txt'
$files = Get-ChildItem C:\ -Recurse | ? {$_.name -match $pattern}
foreach($file in $files){
    ...
}
1
  • No, not really want I'm trying to accomplish. I'll edit the question to be more clear. Commented Mar 19, 2013 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.