Home > Software design >  How to write all the files names from a folder inside a txt file
How to write all the files names from a folder inside a txt file

Time:10-12

With this code I get the data but is not reflected on the txt file. I just get a bunch of Microsoft.PowerShell.Commands.Internal.Format.FormatStartData. Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData

Instead the names of each file.

Here is the code:

   param(
[string]$foldername = 'unknown'
 )

 if (Test-Path $foldername){
$location = Join-Path -Path $HOME -ChildPath "files.txt"
$files = Get-ChildItem $foldername | Where-Object {$_.PsIsContainer -ne $True} | Format-Table 
Name
$amount = Get-ChildItem $foldername | Where-Object {$_.PsIsContainer -ne $True} | Measure- 
Object
Add-Content -Path $location -Value $files
Write-Host $amount.count "filenames were written to file" $location
 }

else {Write-Host "Sorry,", $foldername, "does not exist."
break
 }

CodePudding user response:

First get-childitem supports the switch File, no need to pipe and filter. The Format-Table is used to format the output displayed on the screen, so as you want to write to a file you do not need it.

Also only use break within a loop, if you want to stop the processing use return instead.

param(
    [string]$foldername = 'unknown'
)
    
if (Test-Path $foldername){
    $location = Join-Path -Path $HOME -ChildPath "files.txt"
    #gets all files in the specified path
    $files = Get-ChildItem $foldername -File
    #counts the number of files
    $amount = $files.count
    #If you want the fullpath in the logfile use $files.fullname if you only want the name use $files.name
    $files.FullName | Add-Content -Path $location 
    Write-Host "$amount filenames were written to file $location"
}
else {
    Write-Host "Sorry, $foldername, does not exist."
    return
}
  • Related