PowerShell Directory Listing CSV Export

by Vince
in Blog
Hits: 1626

Kind of an interesting request that took a little bit of manipulation to get what I wanted.  Essentially, we're calling for a directory listing and we want to export that listing into a CSV file.  But we want to remove the directory path in order to get just the filenames.  In addition, instead of explicitly calling the username, I'm using the system variable.  This way, the working folder can be moved and reused on another profile or machine.  I'm also using the system date in the filename to keep the filename unique.  I'm using a .txt file because I'm lazy and I couldn't figure out how to do it in one line.  

$username=$env:UserName
$date=(Get-Date -Format o).Replace(":","-")
$path = "C:\users\$username\"
$newpath = " "
Get-ChildItem c:\users\$username\*.* | Select-Object FullName |
  Export-Csv c:\users\$username\desktop\dir.txt -NoTypeInformation
(Get-Content -path c:\users\$username\desktop\dir.txt) -replace [regex]::Escape($path),
  $newpath | Out-File c:\users\$username\desktop\$date.dir.csv
Remove-Item -path c:\users\$username\desktop\dir.txt


Because Windows has protections against Powershell Script Executions, we can launch this .ps1 file by using:

powershell -ExecutionPolicy ByPass -File c:\[ENTER PATH TO FILE]\dir.ps1