[PowerShell] Get File List as JSON File

This article can be read in about 3 minutes.
PR

The purpose 

I will save files, including those within subfolders on Windows, to a JSON file in JSON format.

PR

Implementation

Make PS1 file

Create a file named file_list.ps1, paste the following content into it, and save it.

Please change the values of $targetPath and $outputPath to match your environment.

$targetPath = "Folder path to create file list from)"
$outputPath = "Output file name"

Get-ChildItem -Path $targetPath -Recurse -File  | Select-Object Name, FullName | ConvertTo-Json |Out-File $outputPath -Encoding UTF8

Example:

$targetPath = "./data"
$outputPath = "./file_list.json"

Get-ChildItem -Path $targetPath -Recurse -File  | Select-Object Name, FullName | ConvertTo-Json |Out-File $outputPath -Encoding UTF8

It seems that $targetPath and $outputPath do not work with Japanese characters. However, Japanese characters in subfolder names or file names are not a problem.

If it doesn’t work, please ensure $targetPath and $outputPath are relative paths or absolute paths.

It is saved in UTF8 for easier use later with JavaScript, etc.

(Fetch generally retrieves JSON in UTF-8)

Execute PS1 file

Launch PowerShell (display the Windows menu, type “Power,” and click the following).

Navigate to the folder where you created the PS1 file using the cd command.

Execute below.

./file_list.ps1
PR

Result

The list of files was successfully saved in JSON format as shown below.

file_list.json

[
{
"Name": "1.txt",
"FullName": "G:\\test\\1.txt"
},
{
"Name": "2.txt",
"FullName": "G:\\test\\2.txt"
}
]

comment

Copied title and URL