Search code examples
powershellcsvexport-to-csv

Make a custom CSV List of files with Powershell


I'm trying to make a CSV file with a list of files that I would use to make a .cpk file with another program.

The list in the CSV should contain only files that are in the Output folder:

    <root folder>
     makecsv.ps1
        Output (the files)

The CSV formatting of the CSV is simple:

    "<full path to file>", "<relative path>", <line number, starting with 0>, Uncompress
    

An example of the output would be:

    "F:/Aemulus/Output/battle/cutin/bct_p_bc0004.dds", "/battle/cutin/bct_p_bc0004.dds", 0, Uncompress
    "F:/Aemulus/Output/sound/motionse/em0000.dat", "/sound/motionse/em0000.dat", 1, Uncompress
    "F:/Aemulus/Output/script/field/fscr0150_002_100.bf", "/script/field/fscr0150_002_100.bf", 2, Uncompress
    

I would write a program for this, but there's a private reason on why I need to have a Powershell script for this, and while I can output simple csv files, I have absolutely no idea on how I should approach this.


Solution

  • This should do it. But I strongly recommend you look up the commands and their parameters in the documentation, so you understand how this code works. Also, feel encouraged to ask as many questions about it as you need to understand it.

    # the "script:" scope prefex is required, so we can change the value later
    $script:lineNumber = 0
    
    # get the full path of the folder, so we can use it to build the relative path later
    $rootPath = Resolve-Path -Path "Output"
    
    # get all files in folder and subfolers
    # then build the desired output using "calculated properties"
    # and finally export to csv file
    Get-ChildItem -Path $rootPath -File -Recurse | Select-Object -Property @{
        Name = "FullPath"
        Expression = "FullName"
    }, @{
        Name = "RelativePath"
        Expression = { $_.FullName.Replace($rootPath, "")}
    }, @{
        Name = "LineNumber"
        Expression = {($script:lineNumber++)}
    }, @{
        Name = "Uncompress"
        Expression = {"Uncompress"}
    } | Export-Csv -Path "export.csv" -NoTypeInformation -Delimiter ","