使用Get-ChildItem与Export-Csv添加文件路径失败的技术求助
Let’s figure out why your modified script is failing and get it working properly. The core issue here is almost certainly incorrect variable context or path handling when trying to use $_.Basename in your export filename. Here’s how to resolve it:
Common Mistake to Avoid
If you tried something like this (directly using $_.Basename in the Export-Csv path without iterating over each object), it won’t work because $_.Basename only has meaning in the context of a single pipeline object, not when processing a collection:
# ❌ This will fail - $_.Basename isn't valid here for individual files Get-ChildItem -Path "C:\Your\Files" | Export-Csv -Path "C:\Exports\$($_.Basename)_output.txt" -NoTypeInformation
Correct Approach: Iterate with ForEach-Object
To reference each file’s Basename correctly, wrap your export logic in ForEach-Object so you’re processing one file at a time, and build your export path safely:
# ✅ Working example: Export each file's data to a unique CSV with its Basename in the filename Get-ChildItem -Path "C:\Your\Source\Directory" -File -Filter *.txt | ForEach-Object { # Step 1: Clean the Basename to remove invalid filename characters (optional but recommended) $safeBasename = $_.Basename -replace '[^\w\-.]', '_' # Step 2: Build the full export path using Join-Path to avoid path separator issues $exportPath = Join-Path -Path "C:\Your\Export\Directory" -ChildPath "$safeBasename_export.csv" # Step 3: Export your data (adjust the Select-Object to match what you need to export) $_ | Select-Object FullName, Length, LastWriteTime, CreationTime | Export-Csv -Path $exportPath -NoTypeInformation -Encoding UTF8 }
Key Notes:
ForEach-Objectgives you per-file context: Inside the script block,$_refers to the current file object fromGet-ChildItem, so$_.Basenameworks as expected.Join-Pathis safer than string concatenation: It automatically handles backslashes/forward slashes based on your OS, avoiding broken paths.- Clean invalid characters: The
-replaceregex removes any characters that aren’t allowed in filenames (like:,*,?) to prevent export errors. - Encoding: Adding
-Encoding UTF8ensures your exported files are readable across systems (optional but helpful).
If You Want a Single Export File with a Basename
If your goal is to export all results to one file that includes a specific Basename (e.g., from the first file in the collection), you can capture the Basename first:
# ✅ Export all files to a single CSV using the first file's Basename $files = Get-ChildItem -Path "C:\Your\Source\Directory" -File -Filter *.txt if ($files) { $exportPath = Join-Path -Path "C:\Your\Export\Directory" -ChildPath "$($files[0].Basename)_all_files.csv" $files | Select-Object FullName, Length, LastWriteTime | Export-Csv -Path $exportPath -NoTypeInformation -Encoding UTF8 }
内容的提问来源于stack exchange,提问作者Peter Core

