Read-Host list of filenames and then export the Input to a csv file

462 views Asked by At

I am trying to do a simply read host and export the user input to a csv file.

$List = Read-Host -Prompt 'Enter List of files (exclude file extention)'|
Export-Csv "c:\user.csv" -NoTypeInformation

All I get in my file is:

"length"
"42"

I think I need to declare a custom object but what I want is:

User inputs:

filename1
filename2

export-csv C:\list.csv should have:

filename1
filename2

Thanks!

1

There are 1 answers

16
Abraham Zinala On

You mentioned using a PSCustomObject, so why not use it?

$R_Input = Read-Host -Prompt "Exclude extension! `nEnter File Name" 
$R_Input = $R_Input -split ","

    [PSCustomObject]@{

        "First File Name"  = $R_Input[0]
        "Second File Name" = $R_Input[1]

    } | Export-Csv -Path "c:\user.csv" -NoTypeInformation -Force -Append

<#Input

Exclude extension! 
Enter File Name: Path Number One, Path Number two

#>


<#OutPut

PS C:\WINDOWS\system32> Import-Csv c:\user.csv

First File Name Second File Name
--------------- ----------------
Name Number One  Name Number two

#>

EDIT:

If you dont care about the file names being in a same column, you can use a for loop to iterate though all input (seperated by a comma), and passed into a PSCustomObject. Now it shouldn't matter how much names they input.

$R_Input = Read-Host -Prompt "Exclude extension! `nEnter File Name" 
$R_Input = $R_Input.Trim() -split ","

    for ($i=0; $i -lt $R_Input.Count; $i++) {
        [PSCustomObject]@{

            "File Name"  = $R_Input[$i]

        } | Export-Csv -Path "c:\user.csv" -NoTypeInformation -Force -Append
    }