如何导出包含文件夹中所有名称的列表的CSV文件?

时间:2019-07-23 10:59:18

标签: powershell csv

我希望创建一个脚本来传递给用户,该脚本询问文件路径位置,并将其中包含的所有文件名导出到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"

提示:

Please enter the path location you wish to export: "C:\Users\khalifam\Desktop\Depositions going into trial bundle"

错误:

Set-Location : Cannot find drive. A drive with the name '"C' does not exist.
At line:3 char:1
+ Set-Location $FilePathLocation
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ("C:String) [Set-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

3 个答案:

答案 0 :(得分:-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
}

答案 1 :(得分:-1)

这似乎可以解决问题。

$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

答案 2 :(得分:-2)

您无需设置位置,只需查询文件列表的完整路径名

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