0

I have to read each file in a folder and determine the length of the first line of each, then do something depending on whether or not that length is what is should be in a table. I can loop through each file in batch and have %%f as the file, but how do I get that length and assign it to a variable?

If there is a way to do this in Powershell using a batch file, that would help, but I would need to know how to call the Powershell from the batch file also.

Phoenix14830
  • 360
  • 1
  • 8
  • 24
  • 2
    You'd better do that in "true" Powershell style, using a Powershell script. It can do a `Get-Content $file` and parse that, it can do `Get-ChildItem` aka `dir` to get the list of files, and of course it can loop via `foreach ($file in $files)`. Variables are also supported, of course, all that starts with a dollar sign is a variable (set or unset). And to call Powershell you can do `powershell -command "powershell commands; more commands; last command"`. – Vesper Jul 28 '15 at 14:25

2 Answers2

1

The simple PowerShell code would look something like this:

param($path)
Get-ChildItem $path -File | 
    Select FullName,@{Label="1stLineLength";Expression={(Get-Content $_.FullName -First 1).Length}}

So the first argument will be taken as the path of the script. Then to call it from batch I borrow the answer to this SO question.

Powershell.exe -executionpolicy remotesigned -File m:\Scripts\firstlinelength.ps1 "C:\temp"

That will get output like this on console.

FullName                              1stLineLength
--------                              -------------
C:\Users\mcameron\CleansedBigFile.txt             4

This code assumes that you have at least PowerShell v3.0 for the -First and -File parameter and switch. I would like to think that most batch code can be converted easily to a PowerShell equivalent so if your environment allows you consider converting to the powerful PowerShell.

Community
  • 1
  • 1
Matt
  • 45,022
  • 8
  • 78
  • 119
0

Some of your question is pretty vague (what table?). But in general, you don't need a batch file at all. PowerShell example:

Get-ChildItem -File | ForEach-Object {
  $firstLineLength = (Get-Content $_ | Select-Object -First 1).Length
  if ( $firstLineLength -gt $whateverFromTable ) {
    ...
  }
}

Note that the -File parameter of Get-ChildItem doesn't exist before PowerShell v3. For PowerShell v2 and below, you would replace Get-ChildItem -File with Get-ChildItem | Where-Object { -not $_.PSIsContainer }.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62