Simple script to move files from one location to another - powershell

I need help with creating a power-shell script that copies folder recursively from one location to another. Here is how I plan to do it:
There will be a list of folders to copy, which are combination of name and ID number.
Create an array to store variables.
Create a loop that will look for each variables in array and copy the folders to another location.
Here is my code to copy a single folder, but I need to make it more feasible so that it can copy folders depending on variables:
$AID = (4069302,4138482)
foreach ($number in $AID ) {
Get-ChildItem "C:\Users\sshres19\Desktop\Script\GAEBox" -Recurse -Filter "*$number*" |
Copy-Item -destination "C:\Users\sshres19\Desktop\Script\Reg"
}
The script needs to copy all folders and files within given condition.

Adding -Recurse to your Copy-Item will make it copy a folder and it's contents.

Related

Powershell: Multiple subfolders named the same. Want all tied to Path variable

Is there a simple way of taking multiple subfolders under the same root and assigning it to a single variable?
My folder structure looks like the following
C:\Unsigned Items\City A\Jeff\Signed
C:\Unsigned Items\City B\Erik\Signed
C:\Unsigned Items\City C\Dave\Signed
I want to assign all of the subfolders named "Signed" to a single variable, such as $srcRoot
I started by just adding each path like the following. It works, but seems inefficient as I have about 50 "cities".
$srcRoot = "C:\Unsigned Items\City A\Jeff\Signed","C:\Unsigned Items\City B\Erik\Signed" ect
So I gather you want an aray of directory fullnames from a source folder where two of the subfolder paths have different named, but all contain a folder called Signed.
Just use Get-ChildItem starting with the path all folders have in common (C:\Unsigned Items) and for the subfolders with different names simply use the wildcard asteriks.
Then take the FullName property from the resulting DirectoryInfo objects:
$srcRoot = (Get-ChildItem -Path 'C:\Unsigned Items\*\*\Signed' -Directory).FullName

get-childitem either subfolder or a "rbac.jsonc" file

I want to check if all folders contains either a subfolder or an rbac.jsonc file.
I want to iterate through a list of folder $topMgFolderPath being the root folder.
I want to go all the way down the tree in the folders
I am are looking to trigger a Pester test failure if there is anything that do not correspond to my condition.
I expect folders to have either a rbac.json file, in which case all the subfolders in that folder will be ignored from any further processing or at least 1 subfolder that will itself contains either a rbac.jsonc file or more subfolders that will lead down the line to such a file.
In all cases, .policy folder is to be ignored
is this somehow possible ?
Your question lack some clarity for me as it stand.
Based on your post, what I understand is:
You want to iterate through a list of folder $topMgFolderPath being the root folder.
You used -Recurse in your code sample so I assumed you want to go all the way down the tree
Based on your second code line ending of | should -BeNullOrEmpty, you are looking to trigger a Pester test failure if there is anything that do not correspond to your condition.
You expect folders to have either a rbac.json file, in which case all the subfolders in that folder will be ignored from any further processing or at least 1 subfolder that will itself contains either a rbac.json file or more subfolders that will lead down the line to such a file.
In all cases, .policy folder is to be ignored
Please update your question with additional details or clarify the situation if I didn't get the premise right.
In any case, what you seek to do is possible but not through a single Get-ChildItem statement.
The way I'd go about it, since you want a recurse operation with multiple checks that stop processing a folder once it has been validated, is an home-made -recurse done through a single-layer Get-ChildItem alongside a queue where the recursion is done "manually", one layer at a time within a while loop that persist until the queue is cleared out.
$topMgFolderPath = 'C:\temp\'
$queue = [System.Collections.Queue]::new()
$InvalidFolders = [System.Collections.Generic.List[PSobject]]::new()
$Directories = Get-ChildItem -path $topMgFolderPath -Exclude '.policy' -Directory
$Directories | % { $queue.Enqueue($_.FullName) }
while ($Queue.Count -gt 0) {
$dir = $queue.Dequeue()
$HasRbacFile = Test-Path -Path "$dir\rbac.json"
# If Rbac file exist, we stop processing this item
if ($HasRbacFile) { Continue }
$SubDirectories = Get-ChildItem -Path $dir -Directory -Exclude '.policy'
# If the rbac file was not found and no subfolders exist, then it is invalid
if ($SubDirectories.count -eq 0) {
$InvalidFolders.Add($dir)
} else {
# Subdirectories found are enqueued so we can check them
$SubDirectories | % {$queue.Enqueue($_.FullName)}
}
}
# Based on your second line of code where you performed that validation.
$InvalidFolders | should -BeNullOrEmpty
Everything important happens in the while loop where the main logic
Is there a rbac file ?
If not, is there any subfolders (not .policy) to check ?
References
Queue Class

Powershell Script that recursively searches for specific file and containing directory and copy it to another location

I'm attempting to write a powershell script that will search recursively for a file and copy it to another location on a local drive with the date appended to it.
However that file could be in multiple different directories. (ex. c:\users\default\Bookmark.txt, c:\users\profile1\Bookmark.txt, c:\users\profile2\Bookmark.txt...etc.)
To distinguish between the different directories I was thinking of appending the directory name containing the file to the filename along with the date. (ex. filename-directoryName-date)
Here is what I have so far:
get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force | copy-item -Destination $env:userprofile\Bookmarks-$(get-date -UFormat %d-%m-%Y)
This works if it only finds 1 copy of the Bookmarks file and it only appends the date.
To figure out the names of the containing folders I used this command.
(get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force).Directory.Name
I need to somehow put this two together and so it outputs :
c:(whateverlocation)\Bookmark-DirectoryName-Date
I hope I'm making sense.
Dan,
When you use the Get-ChildItem command (alias gci) it will return to you an array of DirectoryInfo and FileInfo objects, one for each item it finds. If you are looking for files called "Bookmarks" (or bookmark.txt...can't tell from your examples which one you're looking for) then you can use the following command to get you a list of all of them:
[array]$FileList = gci -Recurse -File -Filter "Bookmarks"
The [array] designation is necessary to be sure the object is an array regardless of how many items are returned. The filter can have wildcards if you don't know the exact filename. What that leaves me with is an array object named $FileList containing all of the information about the files. You can read all about the properties and methods available in these objects at this Microsoft help page.
For this task, we'll need the .FullName property, which tells you the full path & name of each item (which can be used as your source) and the .BaseName & .Extension properties, which give you the filename and extension respectively. Using these properties, you can copy each of the files you find to a destination. Putting it all together, you get something like this:
$SourceFolder = "$($env:userprofile)\AppData\Local\Microsoft\Edge\User Data"
$DestFolder = '' #Path to Destination Folder
[array]$FileList = gci -Path $SourceFolder -Recurse -File -Filter "Bookmarks"
ForEach ($F in $FileList) {
Copy-Item $F.FullName (Join-Path $DestFolder ($F.Name + 'stuff to add to end of filename' + $F.Extension))
}
In this case, since the files are named 'Bookmarks', the $F.Extension should be blank. If using a more traditional filename, the pattern above will help you fit your changes in between the filename and the extension.
Hope this helps you out. If it does, please accept the answer using the check mark on the left.

PowerShell Copy and Rename Files in the same Folder

I have a bunch of file which I like to copy or duplicate in the same folder but renaming part of the filename during the copying...
Ex.
Copying these files
¸Ó¸®30_³²_0.pal
¸Ó¸®30_³²_1.pal
¸Ó¸®30_³²_2.pal
¸Ó¸®30_³²_3.pal
¸Ó¸®30_³²_10.pal
¸Ó¸®30_³²_11.pal
¸Ó¸®30_³²_12.pal
But must be renamed to these
¸Ó¸®31_³²_0.pal
¸Ó¸®31_³²_1.pal
¸Ó¸®31_³²_2.pal
¸Ó¸®31_³²_3.pal
¸Ó¸®31_³²_10.pal
¸Ó¸®31_³²_11.pal
¸Ó¸®31_³²_12.pal
Also I want an input of what to copy and what it will be renamed to...
I only need to input 30_ for the files to copy then input 31_ or 41_ for the copied files..
If it's not possible for input.. I can do with hard coded value...
Update:
I found a code that copies and renames the files..
Get-ChildItem '*30_*.pal' -recurs | % {
$copyto = $_.FullName -replace "30_","41_"
Copy-Item $_.FullName $copyto
}
The input is what's missing now.. and I don't know how to do it...
This should replace the each file if your get-childitem is working properly
Get-ChildItem '*30_*.pal' -Recurse |% {$_.Replace('30','31')}
Ranadip Dutta's answer is good, but the replace might give issues if the second set of numbers ever contains a 30...for example, if there are more files in the group and you have one:
¸Ó¸®30_³²_30.pal
It would get renamed to:
¸Ó¸®31_³²_31.pal
In order to avoid this, use more identifying characters in the Replace to be sure that you are replacing the number in the correct location in the file, like this:
Get-ChildItem '*30_*.pal' -Recurse |% {$_.Replace('®30','®31')}

How do I move files from an old folder structure to new?

I want to modify my existing folder structure. I had a file tree that was organized in the following way:
Client Name
State/Province
City
Order Number
But I have modified it to add an address before the order number separated by a hyphen, as such:
Client Name
State/Province
City
Order Number - Address
I created the new folder structure with a macro I had that generated the original, and I figured this was much easier than renaming the existing folders.
So now I want to upload the empty folders to my server, but before I do that I want to take the files from all the old structure and put them into the new one.
Simply, I am trying to write a script to match the folder name in the original hierarchy to the new hierarchy that contains the original name plus address, and then copy the files in the original folder to the similarly named one in the new structure.
How would I do this? VBA, Powershell, Batch Command? I'm not very well versed in PS.
Use a foreach loop with the Get-ChildItem,
Copy-Item,
and Test-Path Powershell cmdlets:
#Get all address subfolders
$addr_folders = Get-ChildItem c:\"Client Name"\State/Province\City\ -recurse | Where-Object {$_.PSIsContainer -eq $True}
#Loop through all address subfolders
foreach ($address in $addr_folders)
{
#Copy contents from existing subfolder path to new folder
if (Test-Path c:\"Client Name"\State/Province\City\"Order Number"\$address)
{
Copy-Item c:\"Client Name"\State/Province\City\"Order Number" c:\"Client Name"\State/Province\City\"Order Number - " $address
}
}