cww777
cww777

Reputation: 13

Pipe filename from Get-ChildItem into a .csv file

I'm currently writing a powershell script that will look for files the end with xyz.xml. It parses the xml and extracts the needed information into an .csv file. I also need the name of the xyz.xml file in the .csv file for the information to be effective. I currently have:

Get-ChildItem -Filter *-xyz.xml | ForEach-Object{
$F_Name = Select-Object Name
[xml]$XYZFILE = Get-Content $_
$TITLE=$XYZFILE.title
$RELEASE=$XYZFILE.release
$VERSION=$XYZFILE.version
$FILEPATH = "INFO.csv"
$FILEEXISTS= Test-Path $FILEPATH
If(FILEEXISTS -eq $False){
$csv = @"
"File Name","Name","Release","Version"
"$F_NAME","$TITLE","$RELEASE","$VERSION"
"@
}
ELSE {
$csv = @"
"$F_NAME","$TITLE","$RELEASE","$VERSION"
"@
}
$csv>>$FILEPATH
}

Unfortunately when I run this the column of "File Name" is empty and I'm unsure as to why. Does anyone have any idea as to why I can't get the actual name the of the file that I'm parsing?

Upvotes: 1

Views: 2299

Answers (1)

BenH
BenH

Reputation: 10044

Nothing is getting passed into Select-Object Name. Since you are using ForEach-Object, you will want to pipe the automatic variable $_, which contains the current object in the pipeline. Also, you will want to expand the Name property so that rather than having an object with a property name, your variable will be a string that is the name.

$F_Name = Select-Object Name 

becomes:

$F_Name = $_ | Select-Object -ExpandProperty Name

or you could use the dot property notation:

$F_Name = $_.Name

You script could also be simplified by making an array of objects and then using the Export-CSV -Append command to add them to the CSV file.

$FILEPATH = "INFO.csv"
Get-ChildItem -Filter *-xyz.xml |
    ForEach-Object {
        [xml]$XYZFILE = Get-Content $_
        [PSCustomObject]@{
            "File Name" = $_.Name
            "Name" = $XYZFILE.title
            "Release" = $XYZFILE.release
            "Version" = $XYZFILE.version
        }
    } |
    Export-CSV $FILEPATH -Append

Upvotes: 1

Related Questions