Powershell script to create folders from list of names in a file

TheManBehindTheMan picture TheManBehindTheMan · Nov 15, 2017 · Viewed 9k times · Source

I have a text file that contains a list of files in different directories, e.g

  • C:\FolderOne\Testing.jpg
  • C:\FolderTwo\Test.jpg

I'd like to turn those names into folders. And if two files exist in one folder, e.g FolderOne, then both those files should go into the same folder.

I understand that the backslashes will also have to be replaced by underscores and the colon replaced by an underscore too.

Thus far, I'm able to get the contents from the file list and copy it into a specified folder. I would like to create a folder for each file in the file list, but the folder name needs to include C_FolderOne and C_FolderTwo and so on....

Any help would be appreciated!

What I have so far:

Param (
    [String]$model
)

# Debug line
$model = "DEV2";

[String]$drive = "C:";

#Go to the PG_dump directory
CD "C:\Program Files\PostgreSQL\9.4\bin"

##Execute PG_dump with no password
.\pg_dump.exe --host localhost --port 5432 --username "postgres" --role "postgres" --no-password  --format custom --blobs --verbose --file     "C:\Test\$date-DEV-$X.backup" "DEV"

#Get the content from the file list
$file_list = Get-Content "$drive\Testing\DEV33.txt" 
foreach ($file in $file_list)
{    
    Copy-Item  $file -Destination "C:\Testing"
}

Answer

Maximilian Burszley picture Maximilian Burszley · Nov 15, 2017

Here's a method to do what you're asking. It'll grab the parent path for the file and create the destination folder.

## Get the content from the file list.
foreach ($file in Get-Content -Path "$drive\Testing\DEV33.txt") {
    $name = (Split-Path -Path $file -Parent) -replace '\\', '_' -replace ':'
    New-Item -Path "path\to\$name" -ItemType Directory
}