Powershell copy only selected files with folder structure - powershell

I have a folder hierarchy with a lot of files.
I need to copy all folders and only selected files. For this purposes I write script:
$path = "D:\Drop\SOA-ConfigurationManagement - Test\181"
$files = Get-ChildItem -Path $path -Recurse | ? { $_.Name -like "system.serviceModel.client.config" }
$Destination = "D:\test\"
Copy-Item $files -Destination $Destination -recurse
When I execute variable $files, it returns correct path:
But when I execute Copy-Item it returns not full path:
Perhaps my approach is wrong. If so, how to copy entire folder structure, and only selected files (in this case system.serviceModel.client.config file)?
UPD1 Ok, I've found, how to copy only folders:
$path = "D:\Drop\SOA-ConfigurationManagement - Test\181\"
$Destination = "D:\test\"
Copy-Item $path $Destination -Filter {PSIsContainer} -Recurse -Force
But how to copy only selected files, preserving their location? What needs to be in $Destination variable?
$files = Get-ChildItem -Path $path -Recurse | ? { $_.Name -like "system.serviceModel.client.config" } | % { Copy-Item -Path $_.FullName -Destination $Destination }

This code would keep the directory structure the same too
$path = "D:\Drop\SOA-ConfigurationManagement - Test\181\"
$Destination = "D:\test\"
$fileName = "system.serviceModel.client.config"
Get-ChildItem -Path $path -Recurse | ForEach-Object {
if($_.Name -like $fileName) {
$dest = "$Destination$(($_.FullName).Replace($path,''))"
$null = New-Item $dest -Force
Copy-Item -Path $_.FullName -Destination $dest -Force
}
}

To copy the whole folder structure AND files with a certain name, below code should do what you want:
$Source = 'D:\Drop\SOA-ConfigurationManagement - Test\181'
$Destination = 'D:\test'
$FileToCopy = 'system.serviceModel.client.config'
# loop through the source folder recursively and return both files and folders
Get-ChildItem -Path $Source -Recurse | ForEach-Object {
if ($_.PSIsContainer) {
# if it's a folder, create the new path from the FullName property
$targetFolder = Join-Path -Path $Destination -ChildPath $_.FullName.Substring($Source.Length)
$copyFile = $false
}
else {
# if it's a file, create the new path from the DirectoryName property
$targetFolder = Join-Path -Path $Destination -ChildPath $_.DirectoryName.Substring($Source.Length)
# should we copy this file? ($true or $false)
$copyFile = ($_.Name -like "*$FileToCopy*")
}
# create the target folder if this does not exist
if (!(Test-Path -Path $targetFolder -PathType Container)) {
$null = New-Item -Path $targetFolder -ItemType Directory
}
if ($copyFile) {
$_ | Copy-Item -Destination $targetFolder -Force
}
}

try this
$path = 'D:\Drop\SOA-ConfigurationManagement - Test\181\'
$Destination = 'D:\test\'
$files = Get-ChildItem -Path $path -Recurse -File | where Name -like "*system.serviceModel.client.config*" | %{
$Dir=$_.DirectoryName.Replace($path, $Destination)
$NewPAthFile=$_.FullName.Replace($path, $Destination)
#create dir if not exists
New-Item -Path $Dir -ItemType Directory -Force -ErrorAction SilentlyContinue
#copy file in new dir
Copy-Item $_.FullName $NewPAthFile
}

With minimal changes I'd suggest the following:
$path = "D:\Drop\SOA-ConfigurationManagement - Test\181"
$files = Get-ChildItem -Path $path -Recurse | ? { $_.Name -like "system.serviceModel.client.config" }
$Destination = "D:\test\"
$files | % { $_ | Copy-Item -Destination $Destination -recurse }
You can even put the whole copy on one line:
$path = "D:\Drop\SOA-ConfigurationManagement - Test\181"
$Destination = "D:\test\"
Get-ChildItem -Path $path -Recurse | ? { $_.Name -like "system.serviceModel.client.config" } | % { $_ | Copy-Item -Destination $Destination -recurse }
Copy-Item can find the path from the stream of input objects but it doesn't seem to be able to take a collection of System.IO.FileInfo objects as an argument to Path.

Related

is file a child of given folder in PS? [duplicate]

Trying to get my copy-item to copy everything in directory except a subfolder. I was able to exclude in the folder and files, but not subfolders.
I tried using get-children and the -exclude in the copy-item but didn't exclude them as I hope
$exclude = "folder\common"
Get-ChildItem "c:\test" -Directory |
Where-Object{$_.Name -notin $exclude} |
Copy-Item -Destination 'C:\backup' -Recurse -Force
Hoping that the common folder will exist but nothing in it would be copy.
Thanks for the help
I think this should do what you need:
$sourceFolder = 'C:\test'
$destination = 'C:\backup'
$exclude = #("folder\common") # add more folders to exclude if you like
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
Get-ChildItem -Path $sourceFolder -Recurse -File |
Where-Object{ $_.DirectoryName -notmatch $notThese } |
ForEach-Object {
$target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourceFolder.Length)
if (!(Test-Path -Path $target -PathType Container)) {
New-Item -Path $target -ItemType Directory | Out-Null
}
$_ | Copy-Item -Destination $target -Force
}
Hope that helps
I think using the -exclude parameter on Get-ChildItem would work:
$exclude = 'Exclude this folder','Exclude this folder 2','Folder3'
Get-ChildItem -Path "Get these folders" -Exclude $exclude | Copy-Item -Destination "Send folders here"
Here is an example:
$exclude= 'subfolderA'
$path = 'c:\test'
$fileslist = gci $path -Recurse
foreach ($i in 0..$fileslist){ if( -not ($i.Fullname -like "*$($exlusion)*")){ copy-item -path $i.fullname -Destination 'C:\backup' -Force } }

How to log copied items during the backup script?

I need to make basic / or more advanced backup script that would copy items from folder A to folder B and then log what it did.
This copies the files just fine:
$source = 'path\gamybinis\*'
$dest = 'path\backup'
Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}| Copy-Item -Destination $dest -Recurse -Force
Write-Host "Backup started"
Pause
But after this I can't write the log with | Out-File, So I've tried this:
$source = 'path\gamybinis\*'
$dest = 'path\backup'
$logFile = 'path\log.txt'
$items = Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}
foreach($item in $items){
Out-File -FilePath $logFile -Append
Copy-Item -Path "$source\$item" -Destination $dest -Recurse -Force
}
Write-Host "Backup started"
Pause
This one does absolutely nothing, what exactly am I doing wrong?
(Advanced script part would be: backing up recently modified files then files should be archived to .rar/.zip, log file have to have structure that is easily readable and log file should have information which user was working on the device during the backup) - For those who are wondering.
If you can't use robocopy, in pure PowerShell code you could do this
$source = 'path\gamybinis' # no need for '\*' because you're specifying -Recurse
$dest = 'path\backup'
$logFile = 'path\log.txt'
# test if the destination path exists. If not, create it first
if (!(Test-Path -Path $dest -PathType Container)) {
$null = New-Item -Path $dest -ItemType Directory
}
Write-Host "Backup started"
Get-ChildItem -Path $source -Recurse |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } |
ForEach-Object {
$_ | Copy-Item -Destination $dest -Recurse -Force
Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
}
Write-Host "Backup done"
From your comments, I understand you have problems when using the -Container switch.
Below code does not use that and creates the folder structure of the copied files in the backup folder, strictly using Powershell code:
$source = 'path\gamybinis' # no need for '\*' because you're specifying -Recurse
$dest = 'path\backup'
$logFile = 'path\log.txt'
Write-Host "Backup started"
Get-ChildItem -Path $source -File -Recurse |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } |
ForEach-Object {
$target = Join-Path -Path $dest -ChildPath $_.DirectoryName.Substring($source.Length)
if (!(Test-Path $target -PathType Container)) {
# create the folder if it does not already exist
$null = New-Item -Path $target -ItemType Directory
}
$_ | Copy-Item -Destination $target -Force
Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
}
Write-Host "Backup done"

Powershell Move Files To Directory - Maintain Paths?

Trying to make a simple backup script that will do as below:
Move the following
\source\example1.txt
\source\path\example2.txt
To
\dest\example1.txt
\dest\path\example2.txt
At the same time, renaming any files that already exist in dest.
My Code:
$src = "C:\Users\User\Desktop\test1"
$dest = "C:\Users\User\Desktop\test2"
Get-ChildItem -Path $src -Filter *.txt -Recurse | ForEach-Object {
$num=1
$nextName = Join-Path -Path $dest -ChildPath $_.name
while(Test-Path -Path $nextName)
{
$nextName = Join-Path $dest ($_.BaseName + " ($num)" + $_.Extension)
$num+=1
}
$_ | Move-Item -Destination $nextName
}
This almost works but it flattens all files into one folder in the dest.
(\source\path\example.txt becomes \dest\example.txt)
How to fix?
Following commented code snippet could do the job:
Get-ChildItem -Path $src -Filter *.txt -Recurse |
ForEach-Object {
$num=1
# ChildPath ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
$nextName = Join-Path -Path $dest -ChildPath $_.FullName.Replace("$src\", '')
# effective destination for current file
$destNew = $nextName | Split-Path
# create effective destination silently if necessary
if ( -not (Test-Path -Path $destNew) ) {
$null = New-Item $destNew -ItemType Directory
}
while(Test-Path -Path $nextName)
{
# ↓↓↓↓↓↓↓↓
$nextName = Join-Path $destNew ($_.BaseName + " ($num)" + $_.Extension)
$num+=1
}
$_ | Move-Item -Destination $nextName
}
Other method :
function Get-ItemNameWithNumberIfExist($NewPath, $BaseName, $Extension, $rang)
{
#build a new file name
if ($rang -eq 0)
{
$NewFileName="{0}{1}" -f $NewPath, $BaseName, $Extension
}
else
{
$NewFileName="{0}({1}){2}" -f $NewPath, $BaseName, $rang, $Extension
}
#build a new path file name (use combine for work on every SE)
$NewPathFile=[System.IO.Path]::Combine($NewPath, $NewFileName)
#recursive call if file exist
if (Test-Path -Path $NewPathFile)
{
$rang++
Get-ItemNameWithNumberIfExist $NewPath $BaseName $Extension $rang
}
else
{
$NewPathFile
}
}
$OldPath='C:\temp\tmp1\'
$NewPath='C:\temp\tmp2\'
Get-ChildItem $OldPath -file -Recurse | %{
$NewPath=$_.DirectoryName.Replace($OldPath, $NewPath)
#create directory without error if exist
New-Item -ItemType Directory -Path $NewPath -Force
#move item and rename if exist
move-item $_.FullName (Get-ItemNameWithNumberIfExist $NewPath $_.BaseName $_.Extension 0)
}

Copy-item exclude Sub-folders

Trying to get my copy-item to copy everything in directory except a subfolder. I was able to exclude in the folder and files, but not subfolders.
I tried using get-children and the -exclude in the copy-item but didn't exclude them as I hope
$exclude = "folder\common"
Get-ChildItem "c:\test" -Directory |
Where-Object{$_.Name -notin $exclude} |
Copy-Item -Destination 'C:\backup' -Recurse -Force
Hoping that the common folder will exist but nothing in it would be copy.
Thanks for the help
I think this should do what you need:
$sourceFolder = 'C:\test'
$destination = 'C:\backup'
$exclude = #("folder\common") # add more folders to exclude if you like
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
Get-ChildItem -Path $sourceFolder -Recurse -File |
Where-Object{ $_.DirectoryName -notmatch $notThese } |
ForEach-Object {
$target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourceFolder.Length)
if (!(Test-Path -Path $target -PathType Container)) {
New-Item -Path $target -ItemType Directory | Out-Null
}
$_ | Copy-Item -Destination $target -Force
}
Hope that helps
I think using the -exclude parameter on Get-ChildItem would work:
$exclude = 'Exclude this folder','Exclude this folder 2','Folder3'
Get-ChildItem -Path "Get these folders" -Exclude $exclude | Copy-Item -Destination "Send folders here"
Here is an example:
$exclude= 'subfolderA'
$path = 'c:\test'
$fileslist = gci $path -Recurse
foreach ($i in 0..$fileslist){ if( -not ($i.Fullname -like "*$($exlusion)*")){ copy-item -path $i.fullname -Destination 'C:\backup' -Force } }

Powershell: Loop through sub-directories and move files

I'm targeting simple task.
I would like to create folder of constant name "jpg" in all subfolders of supplied root folder "D:Temp\IMG" and move all files in every subfolder with extension ".jpg" to that newly created "jpg" folder.
I thought I'll be able to solve this by myself without deep knowledge of powershell, but it seems I have to ask.
So far, I created this code
$Directory = dir D:\Temp\IMG\ | ?{$_.PSISContainer};
foreach ($d in $Directory) {
Write-Host "Working on directory $($d.FullName)..."
Get-ChildItem -Path "$($d.FullName)" -File -Recurse -Filter '*.jpg' |
ForEach-Object {
$Dest = "$($d.DirectoryName)\jpg"
If (!(Test-Path -LiteralPath $Dest))
{New-Item -Path $Dest -ItemType 'Directory' -Force}
Move-Item -Path $_.FullName -Destination $Dest
}
}
What I'm getting out of this is infinite loop of folder "jpg" creation in every subfolder.
Where is my code and logic failing here, please?
The following script would do the job.
$RootFolder = "F:\RootFolder"
$SubFolders = Get-ChildItem -Path $RootFolder -Directory
Foreach($SubFolder in $SubFolders)
{
$jpgPath = "$($SubFolder.FullName)\jpg"
New-Item -Path $jpgPath -ItemType Directory -Force
$jpgFiles = Get-ChildItem -Path $SubFolder.FullName -Filter "*.jpg"
Foreach($jpgFile in $jpgFiles)
{
Move-Item -Path $jpgFile.FullName -Destination "$jpgPath\"
}
}
This will accomplish what you are attempting, I'm pretty sure. Your original script doesn't actually recurse, despite specifying that you want it to (Get-ChildItem has some finicky syntax around that), so I fixed that. Also fixed my suggestion (I forgot that the Extension property includes the preceding dot, so 'FileName.jpg' has '.jpg' as the extension). I added in some checking, and have it throw warnings if the file already exists at the destination.
$Directory = dir D:\Temp\IMG\ -Directory
foreach ($d in $Directory) {
Write-Host "Working on directory $($d.FullName)..."
Get-ChildItem -Path "$($d.fullname)\*" -File -Recurse -filter '*.jpg' |
Where{$_.Directory.Name -ne $_.Extension.TrimStart('.')}|
ForEach-Object {
$Dest = join-path $d.FullName $_.Extension.TrimStart('.')
If (!(Test-Path -LiteralPath $Dest))
{New-Item -Path $Dest -ItemType 'Directory' -Force|Out-Null}
If(Test-Path ($FullDest = Join-Path $Dest $_.Name)){
Write-Warning "Filename conflict moving:`n $($_.FullName)`nTo:`n $FullDest"
}Else{
Move-Item -Path $_.FullName -Destination $Dest -Verbose
}
}
}