【问题标题】:How do I export a CSV file with a list of all the names contained in the folder?如何导出包含文件夹中所有名称列表的 CSV 文件?
【发布时间】:2026-02-13 18:15:01
【问题描述】:

我希望创建一个脚本传递给用户,该用户询问文件路径位置并将其中包含的所有文件名导出为 CSV,目录必须是文件夹。

# set the variable $FilePathLocation to whatever the user specifies
$FilePathLocation = Read-Host -Prompt 'Please enter the path location you wish to export'

# set the working directory
Set-Location $FilePathLocation 

# select the names of all the content in the folder and pop it in to a CSV file within the location
dir -Recurse | Select Name | ConvertTo-Csv | Out-File "test.csv"

提示:

请输入您要导出的路径位置:“C:\Users\khalifam\Desktop\Depositions 进入试用包”

错误:

设置位置:找不到驱动器。名为“C”的驱动器不存在。 在行:3 字符:1 + 设置位置 $FilePathLocation + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: ("C:String) [Set-Location], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

【问题讨论】:

  • 您在路径中使用了" 还是'?试试吧,只要 C:\bla\bla
  • 您的计算机没有驱动器"C:(请注意错误消息中的前导双引号)。输入不带双引号的路径,或在输入路径后去掉前导/尾随双引号。
  • 哎呀,我的错,它是“,我在没有语音标记的情况下尝试了它,效果很好。谢谢大家
  • & 还有我如何进行导出显示或在子文件夹中显示某种内容指示,因为它目前只是一个平面项目列表@AnsgarWiechers
  • Select Name -> Select FullName。另外,请使用Export-Csv 而不是ConvertTo-Csv | Out-FileGet-ChildItem $FilePathLocation -Recurse | Select-Object FullName | Export-Csv 'test.csv' -NoType

标签: powershell csv


【解决方案1】:

试试这样的:

$directoryName = Read-Host -Prompt "Enter the directory to create a file listing csv for"
if(Test-Path $directoryName -PathType Container) {
  $csvPath = Join-Path -Path $directoryName -ChildPath "depositions.csv"
  Get-ChildItem -Path $directoryName -Recurse | Select-Object FullName | Export-Csv -Path $csvPath -NoTypeInformation
  "Your file has been created at: {0}" -f $csvPath
} else {
  "{0} is not a directory.  Please enter a directory when prompted." -f $directoryName | Write-Warning
}

【讨论】:

  • 有什么方法可以清楚地指示子文件夹而无需读取文件路径名?可能是文件夹名称的行间距或粗体字符?
  • @Khalifa96 CSV 是纯文本格式。无法格式化值。您可以将目录和文件名导出为单独的字段:Select DirectoryName, Name.
  • @AnsgarWiechers,那好多了,非常感谢你
  • @phiz 这个答案也与所提出的问题无关(尽管 OP 在 cmets 中移动了目标)。该问题描述了一个由在提示符处输入的文本中的简单印刷错误引起的问题,因此应该删除。
  • @AnsgarWiechers 我不同意你的意见。我的答案 1) 导出一个包含在文件夹中的名称的 csv 2) 询问文件路径位置和 3) 验证输入是一个文件夹。 OP 对他们自己问题的回答反映了我的问题。
【解决方案2】:

这似乎可以解决问题。

$FilePathLocation = Read-Host -Prompt 'Please enter the path location you wish to export'

Set-Location $FilePathLocation 


Get-ChildItem $FilePathLocation -Recurse | Select-Object DirectoryName, Name | Export-Csv 'FileNames.csv' -NoType

【讨论】:

    【解决方案3】:

    无需设置位置,查询文件列表的全路径名即可

    $FileList = dir -recurse $FilePathLocation
    $FileList | Select Name | Export-Csv -Path 'c:\test.csv'
    

    【讨论】:

    • 这是真的,但没有解决 OP 所询问的问题。
    • 也许不是,但很确定这就是他正在寻找的结果
    • OP 正在使用的代码也会这样做。同样,这不是手头的问题。请阅读错误消息和我对问题的评论。
    最近更新 更多