I am wanting to create a script to accomplish the following:

Check all folder in a directory for folders that begin with “2017”

For each folder that begins with 2017, I want to copy that file to another location but with the same name of the folder it came from.

Once the file has been copied it can be deleted from the original location.

5 Spice ups

Sounds not too tough. What have you tried? Where are you stuck? We’re happy to help but not a script writing service.

Post what you have and we’ll go from there.

# look into get-childitem for the folder
get-childitem 
# look into robocopy for the copy process / or copy-item
robocopy $source $destination
copy-item $source $destination

If you post code, please use the ‘Insert Code’ button. Please and thank you!

codebutton_small.png

$maindirectory = "\\server\share"
$destination = "\\newserver\share"
ForEach ($item in Get-ChildItem $maindirectory -Directory) {
	If ($item.name.startswith("2017") {
		Try {
			Copy-Item "$maindirectory\$item" "$destination\$item" -Recurse -ErrorAction "Stop"
			Remove-Item "$maindirectory\$item" -Recurse
		}
		Catch {
			Write-Error "Unable to copy $item. Did not delete."
		}
	}
}
1 Spice up

I am getting an error. It does not seem to like that “-Directory” Says a parameter cannot be found that matches parameter name “Directory”

You’re running an old version of Powershell, look into pstcontainer

Get-ChildItem -Recurse | where-object { $_.PSIsContainer }

This almost works except here is the folder structure:

maindirectory = C:\data\folders\foldername\2017foldername1

destination = C:\data\newfolders\foldername\2017foldername1

I need to be able to grab the name of the folder one level up from the 2017 folder I am trying to copy. So I feel like I am missing one line.

Hello Samuel, There are several ways to manage this. If you obtain the file path as an object, e.g.:

$data = GetChildItem $SomeTopLevelPath -recurse

$data will contain Objects and they will have Methods and properties. You can learn what these are using:

$data[0] | Get-Member
$data[1] | gm

gm is the alias for Get-Member You’ll see there are means to programmatically determination if an object is a file or a directory, what its name is, parts of the Path, et al. This can be used to script your data management. If you take a path object an make it a string:

$filepath = $data[0] | select -exp fullname

-exp is the alias for expandProperty and returns a string. Fullname of a file object returns the entire path which you can manipulate using regular expressions to get the parent of a 2017* directory.