Search folder for filename and copy item to another location - powershell

Hello in our environment we have the following structure:
\\server\share1\Subfolder1\Subfolder3\123456.jpg
\\server\share1\Subfolder2\Subfolder4\456789.jpg
\\server\share2\123456.tif
\\server\share2\456789.tif
What I want to do is the following: Check if the item exists in share2 as tif. If so then I want to copy the tif file to the same location as the jpg (share1).
Via Get-ChildItem -Recurse -File I can get all the files, but I don't know how to compare the filename to share2 and copy the tif file to the same location as the jpg.
Thanks in advance!

This should do what you need:
$JpgFiles = Get-ChildItem .\Share1 -Recurse -File -Filter *.jpg
ForEach ($File in $JpgFiles) {
$TifFile = Get-ChildItem .\Share2 -Recurse -File -Filter *.tif | Where { $_.BaseName -eq $File.BaseName }
If ($TifFile) { Copy-Item -Path $TifFile.FullName -Destination $File.DirectoryName }
}
Gets all the .jpg files in Share1
Iterates through each file and compares the .basename property to the files in Share2 (basename is the file name without the extension).
If it returns a file, copies that file to share1

Related

Powershell: Moving named files to their corresponding folder

enter image description hereI have a folder which has a bunch of files named: WBF123456, WBF135464, etc. These files need to be moved to the corresponding folder. At the moment I am using the commandline to manually enter the numbers of each file so they get moved, using this code:
$files = $args[0]
mv O:\SCAN\SecSur\*$files.pdf O:\SPG\G*\*\*$files
How can I automate this process?
It needs to identify the number in the filename, then move it to the folder containing the same number.
Any help would be great. Thanks.
I need to get the files on the left, inside the corresponding folders on the right.
Maybe the below solution will help you. You should change $origin_path and $destination_path
$origin_path= "C:\Users\geralexgr\Desktop\kati\files"
$destination_path = "C:\Users\geralexgr\Desktop\kati\folders"
Get-ChildItem $origin_path -Recurse -Include *.txt | ForEach-Object {
$folder = [regex]::Matches($_.Name, "\d+(?!.*\d+)").value
Move-Item $_.FullName $destination_path\$folder
}
The example will place files under the folders that match the numeric regex.
After powershell execution file WBF12 gets inside 12 folder
Apparently the files to move are .pdf files, so what you can do is get a list of those files in the source folder and then loop over that list to create (if needed) the destination subfolder and move the file there.
Try:
$destinationRoot = 'O:\SPG\G\SomeWhere' # enter the root folder destination path here
$filesToMove = Get-ChildItem -Path 'O:\SCAN\SecSur' -Filter '*.pdf' -File
foreach ($file in $filesToMove) {
$numName = $file.BaseName -replace '\D+' # leaving only the numbers
# create the target path for the file
$targetFolder = Join-Path -Path $destinationRoot -ChildPath $numName
# create that subfolder if it does not already exist
$null = New-Item -Path $targetFolder -ItemType Directory -Force
# now, move the file
$file | Move-Item -Destination $targetFolder
}
Seeing your screenshots, this might be a better approach for you.
$destinationRoot = 'O:\SPG\G\SomeWhere' # enter the root folder destination path here
# get a list of target folders for the files to be moved to and create a lookupHashtable from their names
$targets = #{}
Get-ChildItem -Path $destinationRoot -Directory | Where-Object {$_.Name -match '(\d+)'} | ForEach-Object {
$targets[$matches[1]] = $_.FullName # key is the number, value is the directory fullname
}
# get a list of files to move
$filesToMove = Get-ChildItem -Path 'O:\SCAN\SecSur' -Filter '*.pdf' -File | Where-Object {$_.Name -match '\d+'}
foreach ($file in $filesToMove) {
$numName = $file.BaseName -replace '\D+' # leaving only the numbers
# see if we have a target folder with that same number in its name
if ($targets.ContainsKey($numName)) {
$targetFolder = $targets[$numName]
Write-Host "Moving file $($file.Name) to $targetFolder"
$file | Move-Item -Destination $targetFolder
}
else {
Write-Warning "Could not find a destination folder for file $($file.Name).."
}
}

GET filelists for each subfolders | Each filelist put in txt-file,which placed in folders that it describe and named like this folder

SOLVED
For each subfolder, that contains images *.jpg need to create textfile list of images names (whithout extensions). Textfiles should be named same as its directory
For example you have same directory scheme:
C:\scriptfolder\ - Parentfolder for filelist_script.ps1
C:\scriptfolder\subfolder1\ - contains some jpg-files
C:\scriptfolder\subfolder2\ - contains some jpg-files
C:\scriptfolder\subfolderN\ - contains some jpg-files
Result of script work will be:
C:\scriptfolder\subfolder1\subfolder1.txt
"subfolder1.txt" - List of all images(.jpg) in "subfolder1"
C:\scriptfolder\subfolder2\subfolder2.txt
"subfolder2.txt" - List of all images(.jpg) in "subfolder2"
C:\scriptfolder\subfolderN\subfolderN.txt
"subfolderN.txt" - LList of all images(.jpg) in "subfolderN"
SOLUTION:
$gl = Get-Location
$folderlist = Get-ChildItem -path $gl\ -Recurse -Directory -Name
foreach ($folder in $folderlist) {
Get-ChildItem $gl\$folder\*.jpg -File |
Foreach-Object {$_.BaseName} |
Out-file -path $gl\$folder\$folder.txt -Force;
}
Using "BaseName" parametr excludes file-extensions from shown data.
Change it to "Name", if you need to get files names whith extension.
Your question isn't very well asked, it is hard to understand exactly what you are asking. By the looks of it you want to get a list of directories containing a single _ and then every .jpg file inside those folders appending it to a text file. This is pretty simple:
$folder = "C:\Users\user\Documents"
foreach ($subfolder in (Get-childitem -Directory $folder\*test*)) {
Get-Childitem $subfolder -Name -filter *.csv | Out-file pctrlst.txt -append
}
There are a few issues in your code:
$subfldr = Get-childitem -Name -Directory *_*
The usage of -Name here returns only the folder name, not the full path. If you are changed to that directory in PowerShell then it won't be an issue but there is no need for that flag.
$pctrlst = Get-childitem -Name -Include *.jpg
-Include needs to be changed to -Filter
$subfldr | ForEach-Object { $pctrlst | out-file pctrlst.txt }
Here you are piping the names of the folders (not the path just the name) to an object loop where you are simply running Out-File on the same variable which holds however many jpg files that are located in the current directory. You are just overwriting the same file with the same data multiple times here.

How do I copy root folder and contents if content in file is true?

To give some context, I have two root folders, one source and one destination. I am trying to write a PowerShell script that goes through a specific file in each folder and if that file meets the criteria, the entire folder of that file gets copied over.
Currently, I am only able to copy the contents of the folder and not the entire folder itself.
I found that using (Get-Item $files).Directory gets me the path of the file it's checking. However, when I use Get-Item -Path $fileRoot -Recurse it comes back saying that -Recurse is unknown.
Below is the full script.
$files = Get-ChildItem -Path "C:\testPath\source\*\content*.xml"
$files | ForEach-Object {
$file = [xml](Get-Content $_.FullName);
$nodeXML = $file.SelectNodes("//*[local-name()='testPathq']");
if ($file.ParentNode.InnerXml.Contains('testPathq') -eq $nodeXML) {
$fileRoot = (Get-Item $files).Directory
$destination = 'C:\testPath\destination\'
Get-ChildItem -Path $fileRoot -Recurse |
Copy-Item -Destination $destination -Force
}
}

Powershell file copy and rename based on path

I have folder Main that has many subfolders (AA,AB,AC,...,ZZ), every subfolder has 5 folders (1,2,3,4,5) in which one them can have .csv file.
I need a to write a script that would copy every .csv file into output folder and rename it based on in which subfolder it was found (AA.csv, BB.csv and so on) all I managed to do was get a list of csv files and create output folder.
New-Item C:\Output -force
$FileExtension = ".csv"
$Dir = get-childitem $FolderPath -recurse
$List = $Dir | where {$_.extension -eq $FileExtension}
$List | format-table Name
I suppose you can have multiple csv files into your dirs, i propose this solution
$Pathsource="C:\Temp\" # let the '\'
$Pathdestination="C:\Temp2\"
#remove -whatif if its ok
Get-ChildItem $Pathsource -Recurse -Filter "*.csv" | %{Copy-Item $_.FullName ($Pathdestination + $_.FullName.Replace($Pathsource , '').Replace('\', '_')) -WhatIf}

How to batch copy and rename files from one folder to another?

I have 100 folders containing a psd file:
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameX\psd\logo.psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameY\psd\logo.psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameZ\psd\logo.psd
...
Each psd file contains a picture:'logo.psd'
I want to copy 'logo.psd' of 'filenameX', 'filenameY', 'filenameZ' located respectively in,
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameX\psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameY\psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\ET2013\filenameZ\psd
...
to another folder,
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\Logos\
and rename 'logo' file with 'logo_parentfoldername' this way: 'logo_filenameX','logo_filenameY', 'logo_filenameZ'.
End Result:
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\Logos\logo_filenameX.psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\Logos\logo_filenameY.psd
C:\Users\Harvey\Documents\Archive011112\TFG\SG\ET\Logos\logo_filenameZ.psd
....
Hope it's clear!
Something like this should do the trick.
You want to use Get-ChildItem with -Recurse to grab all those files within each subdirectory.
Get-ChildItem -Path $dir -Recurse
But filter your results to only those with the .psd extension.
|?{$_.Extension -eq ".psd"}
Then for each of those files get the name of the parent's parent directory.
$_.Directory.Parent.Name
And finally copy the file to our new file destination.
Copy-Item $_.FullName $copyto
So the end product looks something like this:
$dir = "C:\source\"
$destination = "C:\destination\"
Get-ChildItem -Path $dir -Recurse | ?{$_.Extension -eq ".psd"} | % {
$copyto = $destination + $_.Directory.Parent.Name + ".psd"
Copy-Item $_.FullName $copyto
}