[英]How can I find the length of the first line of a file in batch or powershell
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?
我可以批量遍历每个文件并将%% f作为文件,但是如何获取该长度并将其分配给变量?
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. 如果可以使用批处理文件在Powershell中执行此操作,那将有所帮助,但我还需要知道如何从批处理文件中调用Powershell。
The simple PowerShell code would look something like this: 简单的PowerShell代码如下所示:
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 .
然后从批处理中调用它,我借用了这个SO问题的答案。
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. 该代码假定您至少具有
-First
和-File
参数和开关的PowerShell v3.0。 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. 我想可以将大多数批处理代码轻松转换为等效的PowerShell,因此,如果您的环境允许您考虑转换为功能强大的PowerShell。
Some of your question is pretty vague (what table?). 您的某些问题非常模糊(在哪张桌子上?)。 But in general, you don't need a batch file at all.
但是通常,您根本不需要批处理文件。 PowerShell example:
PowerShell示例:
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. 请注意,PowerShell v3之前不存在
Get-ChildItem
的-File
参数。 For PowerShell v2 and below, you would replace Get-ChildItem -File
with Get-ChildItem | Where-Object { -not $_.PSIsContainer }
对于PowerShell v2及以下版本,
Get-ChildItem -File
替换为Get-ChildItem | Where-Object { -not $_.PSIsContainer }
Get-ChildItem | Where-Object { -not $_.PSIsContainer }
. Get-ChildItem | Where-Object { -not $_.PSIsContainer }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.