Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-Item and exclude folders

Tags:

powershell

I need to copy all of my c:\inetpub directory to a new location but exclude the following folders and their subfolders:

c:\inetpub\custerr
c:\inetpub\history
c:\inetpub\logs
c:\inetpub\temp
c:\inetpub\wwwroot

So far I am doing this:

# Directory name is created with a format string
$dirName = "\\servername\folder1 _ {0}\inetpub" -f (get-date).ToString("yyyy-MM-dd-hh-mm-ss")
$dirName # Check the output

# Create dir if needed
if(-not (test-path $dirName)) {
    md $dirName | out-null
} else {
    write-host "$dirName already exists!"
}

#Copy Backup File to Dir
Copy-Item "\\servername\c$\inetpub\*" $dirName -recurse
like image 601
MJJM Avatar asked Aug 19 '15 14:08

MJJM


People also ask

Does copy-item overwrite?

Copy-Item simply overwrites the files and folders on the destination path and the copies newer files. For example, To copy files from the source folder C:\Test1 to the destination folder C:\Test2 below command is used and it simply overwrites the file without asking.

How do I exclude a subfolder in PowerShell?

To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.

What does copy-Item do in PowerShell?

The Copy-Item cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it can't copy a file to a certificate drive. This cmdlet doesn't cut or delete the items being copied.


2 Answers

This is a simple example of something you could do. Build an array of the parent folders that you want to exclude. Since you are accessing them via UNC paths we cannot really use the c:\ path (We can get around this but what I am about to show should be good enough.).

Then use Get-ChildItem to get all the folders in the inetpub directory. Filter out the exclusions using -notin and pass the rest to Copy-Item

$excludes = "custerr","history","logs","temp","wwwroot"
Get-ChildItem "c:\temp\test" -Directory | 
    Where-Object{$_.Name -notin $excludes} | 
    Copy-Item -Destination $dirName -Recurse -Force

You need at least PowerShell 3.0 for this to work.

like image 104
Matt Avatar answered Sep 19 '22 23:09

Matt


Copy-Item -Path (Get-Item -Path "$path\*" -Exclude ('Folder1', 'File.cmd', 'File.exe', 'Folder2')).FullName -Destination $destination -Recurse -Force

Replace:

$path by your source folder

('Folder1', 'File.cmd', 'File.exe', 'Folder2') by your specific files/folder to exclude

$destination by your destination folder

like image 23
JohnM Avatar answered Sep 20 '22 23:09

JohnM