Solved

Powershell script to list files, create folders and move files to them

Posted on 2016-11-08
3
48 Views
Last Modified: 2016-11-08
Hi,

I need a script to
- read files from a directory
- for each file
  -> create a folder with the file name, stripping it for the file extension
  -> move the file to the newly created folder

The files have a long name with spacings. Anyone that can help me with finding a solution to this?
0
Comment
Question by:Kenneth Endestad
3 Comments
 
LVL 67

Assisted Solution

by:sirbounty
sirbounty earned 250 total points
ID: 41878586
Something like this?

$files = get-childitem c:\parentFolder
foreach ($file in $files) {
    $folderName = $file.name.Replace($file.Extension,'')
    new-item -Path $folderName -ItemType directory
    move-item $file.fullname $folderName -Force
}

Open in new window

0
 
LVL 84

Accepted Solution

by:
oBdA earned 250 total points
ID: 41878593
Assuming the target folders should be created in the same folder where the files were coming from.
It's in test mode and will only what it would normally do; remove the two "WhatIf"s in line 5 and 7 to run it for real.
$Source = "C:\Temp"
Get-ChildItem -Path $Source -File | ForEach-Object {
	$TargetPath = Join-Path -Path $Source -ChildPath $_.Basename
	If (-not (Test-Path -Path $TargetPath)) {
		New-Item -Path $TargetPath -ItemType Directory -WhatIf
	}
	Move-Item -Path $_.FullName -Destination $TargetPath -Force -WhatIf
}

Open in new window


sirbounty,
you're processing folder as well, and the files will land in whatever folder the user happens to be, or fail if the drive happens to be not a FileSystem provider.
0
 

Author Closing Comment

by:Kenneth Endestad
ID: 41878661
Works like a charm
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
This article will help you understand what HashTables are and how to use them in PowerShell.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question