您好我使用下面的代码来计算目录中每个文本文件中的行,然后将该信息存储在一个文件中。问题是输出文件存储了每个文本文件的完整路径: 输出示例:
c:\Text folder\file1.txt,14
c:\Text folder\file2.txt,20
c:\Text folder\file3.txt,25
我需要输出如下:
file1,14
file2,20
file3,25
谢谢你的帮助。这是我的代码:
Clear-Host
Get-ChildItem -re -in $include -ex $exclude $path |
Foreach-Object { Write-Host "Counting $_.FullName"
$fileStats = Get-Content $_.FullName | Measure-Object -line
$linesInFile = $fileStats.Lines
"$_,$linesInFile" } | Out-File $outputFile -encoding "UTF8"
Write-Host "Complete"
答案 0 :(得分:2)
使用Basename
- 对象的FileInfo
属性。
"$($_.BaseName),$linesInFile"
您可以通过执行以下操作来简化行数:
$linesInFile = @(Get-Content -Path $_.Fullname).Count
答案 1 :(得分:0)
使用BaseName
属性,与完整Get-ChildItem|Get-Member
#Parameters:
# path - the path containing the code files
# outputFile - fully qualified path of the file
# include (Optional) - file mask(s) to include in the count (deafults to *.*)
# exclude (Optional) - file mask(s) to exclude in the count (defaults to none)
# Example (count lines in target path including *.cs but excluding *.designer.cs)
# .\countLOC.ps1 -path "C:\code\MyProject" -outputFile "C:\code\loc.csv" -include "*.cs" -exclude "*.designer.cs"
param( [string]$path=".", # debug current directory if omitted
[string]$outputFile="$env:TEMP\37514786.txt", # debug some file
[string]$include = "*.*",
[string]$exclude = "")
Clear-Host
Get-ChildItem -re -in $include -ex $exclude $path |
Foreach-Object {
Write-Host "Counting $_.FullName"
$fileStats = Get-Content $_.FullName | Measure-Object -line
$linesInFile = $fileStats.Lines
"$($_.BaseName),$linesInFile"
} | Out-File $outputFile -encoding "UTF8"
Write-Host "Complete"
# debug Get-Content $outputFile | Measure-Object -line
答案 2 :(得分:0)
REM VBS
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Dim f, colFiles, objFile
Dim tFolder, tFile
Dim lineToCopy, readFile, strData, strTextFile, arrLines, LineCount
REM This is the Target Folder and File
Set tFolder = fso.GetFolder("C:\target")
Set tFile = tFolder.CreateTextFile("Header_Count1.log", True)
REM This is the Source Folder to count records
Set f = fso.GetFolder("S:\source")
Set colFiles = f.Files
For Each objFile In colFiles
REM passage below finds all .txt files in selected folder
If LCase(fso.GetExtensionName(objFile.Name)) = "txt" Then
strData = fso.OpenTextFile(objFile, ForReading).ReadAll
arrLines = Split(strData, vbCrLf)
REM passage subracts 1 from the .txt file count if there is a header record
LineCount = UBound(arrLines) - 1
tFile.WriteLine "FileName "& objFile.Name & " RecordCount " & LineCount
End If
Next
REM This pops up once the script is complete
Wscript.Echo "File Count Read of " & f &" Complete"
Set fso = Nothing