Reputation: 955
I'm using the below code in PowerShell to get the filenames along with the number rows which is in one folder..
Get-ChildItem -re -in "*.tsv" |
Foreach-Object {
$fileStats = Get-Content $_.baseName | Measure-Object -line
$linesInFile = $fileStats.Lines
Write-Host "$_=$linesInFile"
}
However, im getting the filenames with path.. i tried changing the .Fullname to .Basename im getting error.
Any idea?? Also can we get the output in a text file?
Upvotes: 2
Views: 194
Reputation: 3264
You don't want to use base name in your file stats command, as it needs the full path to the file.
For output, when you need a sub property displayed in a text string directly using write-host you're going to neex to expand that manually by wrapping it in $()
ie: Unless you wrap your default variable $_.name
in $()
, such that it is written $($_.name)
when using it in the Write-Host
command, it will always print out the full path to the file.
Get-ChildItem -re -in "*.tsv" |
Foreach-Object {
$fileStats = Get-Content $_ | Measure-Object -line
$linesInFile = $fileStats.Lines
Write-Host "$($_.name)=$linesInFile"
}
HOWEVER A better method would be just to use Select-Object
to create a hash table of the info you want directly and forgo the For-Each
Loop entirely.
This can be accomplished using this simple one liner:
Get-ChildItem -re -in "*.tsv" | Select-object -property name, @{n='Lines';e={$(Get-Content $_ | Measure-Object -line).Lines}}
You can see we select from the results of GCI
, select-object
returns a hash table, we select the name
property, and we create a calculated property called "Lines" which defines it's name and the expression used to create that property.
To make it s a little clearer I broke it into lines here but it's the same code as above.
Get-ChildItem -re -in "*.tsv" |
Select-object -property name, @{
n='Lines';e={
$(Get-Content $_ | Measure-Object -line).Lines
}
}
Upvotes: 1