I am trying to copy all files changed/created yesterday from a certain folder to another certain folder. It writes errors and also does not paste the files into the folder.
Here is the script:
$DestinationFolder = "D:\Dropbox\Public\Download\New folder"
If(!(test-path $DestinationFolder))
{
New-Item -ItemType Directory -Force -Path $DestinationFolder
}
$EarliestModifiedTime = (Get-date).AddDays(-1).ToString("MM/dd/yyyy")
$Files = Get-ChildItem "C:\Users\Harel Gordon\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\" -File
foreach ($File in $Files)
{
if ($File.LastWriteTime.ToString("MM/dd/yyyy") -eq $EarliestModifiedTime)
{
Copy-Item $File -Destination $DestinationFolder
Write-Host "Copying $File"
}
else
{
Write-Host "Not copying $File"
}
}
Read-Host -Prompt "Press Enter to exit"
These are the errors:
enter image description here
It worked for a while then stopped. do not know why
Related
I am writing a Powershell script to add only new files to a backup. I have a back up folder and then I add a new file after a minute and it copies all the contents where I only want the new file copied.
So as you can see I am get the files and backing them up in the $Destination folder with the timestamp. After a couple of minutes I add a new file and run the script again and it copies the new added file along with all the other files. I only want the new added file to be copied to the new backup.
What do I need to do to incorporate this??
This is my code:
function BackupArtifacts {
Param(
$FileLocation = "C:\TempCopy",
$Destination = "C:\TempCopyBackUp_" + $TimeStamp,
$StartRange = -100,
$NumberOfDays = 5
)
New-Item -ItemType Directory -Force -Path $Destination
$count = 0
foreach ($fileList in Get-ChildItem $FileLocation -recurse)
{
if ($fileList.LastWriteTime -ge ($(Get-Date)).AddDays($StartRange))
{
#Check if file already exists
try {
Copy-Item $fileList.FullName -Destination $Destination -Recurse
Write-Host $fileList.FullName
$count ++
} catch {
Write-Error $_
}
}
}
Write-Host "Backup complete, Number of files backed up:" $count
}
BackupArtifacts $FileLocation $Destination $StartRange $NumberOfDays
I'd like to copy test.csv from folders test1 to test2, only if the file has yesterdays timestamp on. The code I'm currently working with doesn't copy my file and returns:
Not copying ...\Desktop\test1\test.csv
$DestingationFolder = "...\Desktop\test2"
$EarliestModifiedTime = (Get-date).AddDays(-1)
$Files = Get-ChildItem "...\Desktop\test1\test.csv" -File
foreach ($File in $Files)
{
if ($File.LastWriteTime -gt $EarliestModifiedTime)
{
Copy-Item $File -Destination $DestingationFolder
Write-Host "Copying $File"
}
else
{
Write-Host "Not copying $File"
}
}
Expected: Copy test.csv only if it's timestamp is from yesterday
Actual: Nothing happens and get Not copying ...\Desktop\test1\test.csv returned
Not sure if it's worth deleting the question or not but found this worked for me. Mentioned in the comments above, ... is in my paths only to make make them shorter for the question.
$DestingationFolder = "...\Desktop\test2"
$Files = Get-ChildItem "...\Desktop\test1\test.csv" -File
foreach ($File in $Files)
{
if ($File.LastWriteTime -gt (get-date).AddDays(-1).ToString("MM/dd/yyyy HH:mm:ss"))
{
Copy-Item $File -Destination $DestingationFolder
Write-Host "Copying $File"
}
else
{
Write-Host "Not copying $File"
}
}
Windows 10 64-bit. PowerShell 5
You misspelled DestinationFolder and forgot to create the folder %userprofile%\Desktop\test2
$DestinationFolder = "%userprofile%\Desktop\test2"
If(!(test-path $DestinationFolder))
{
New-Item -ItemType Directory -Force -Path $DestinationFolder
}
$EarliestModifiedTime = (Get-date).AddDays(-1)
$Files = Get-ChildItem "%userprofile%\Desktop\test1\test.csv" -File
foreach ($File in $Files)
{
if ($File.LastWriteTime -gt $EarliestModifiedTime)
{
Copy-Item $File -Destination $DestinationFolder
Write-Host "Copying $File"
}
else
{
Write-Host "Not copying $File"
}
}
I've seen similar questions and used them as a basis for what i'm trying to do here. I have a folder with many files that are named like "Author Name - Book Title.azw".
I'd like to create sub-folders for each author and move all their books into that folder. This is the script i have so far. It successfully creates folder for the Authors, but it chokes on the move-item, says Could not find a part of the path.
$files = Get-ChildItem -file
foreach ($file in $files){
$title = $file.ToString().Split('-')
$author = $title[0]
if (!(Test-Path $author))
{
Write-Output "Creating Folder $author"
New-Item -ItemType Directory -Force -Path $author
}
Write-Output "Moving $file to $author"
Move-Item -Path $file -Destination $author -Force
}
You have to use this:
Get-ChildItem -file | foreach {
$title = $_.ToString().Split('-')
$author = $title[0]
if (!(Test-Path $author))
{
Write-Host "Creating Folder $($author)"
New-Item -ItemType Directory -Force -Path "$author"
}
Write-Host "Moving $($_) to $($author)"
Move-Item -Path "$_" -Destination "$author" -Force
}
You must surround file paths in double quotes. So your code was not working.
From my understanding, you want to move files in a directory to sub folders where the author names are used as the sub folder names. You can try this solution to achieve this.
# Folder which contains files
$Path = "PATH_TO_FILES"
# Make sure path is a directory
if (Test-Path $Path -PathType Container) {
# Go through each file in folder
Get-ChildItem -Path $Path | ForEach-Object {
# Get full path of file
$filePath = $_.FullName
# Extract author
$author = $_.BaseName.Split("-")[0].Trim()
# Create subfolder if it doesn't exist
$subFolderPath = Join-Path -Path $Path -ChildPath $author
if (-not (Test-Path -Path $subFolderPath -PathType Container)) {
New-Item -Path $subFolderPath -ItemType Directory
}
# Move file to subfolder
Move-Item -Path $filePath -Destination $subFolderPath
}
}
I have created a script to copy the folder/sub folders/files from a specific location to a list of servers that I specified on a notepad.
It checks that if the folder has not been created, it will create it and copy over the files, but if the folder has already been created - then it stops.
However, I would like to still copy over newer files even if that folder has already been created, albeit with no subfolders or files in there.
My current code
[String] $KfxComputers = "C:\temp\Kofax Apps\servers.txt"
# This file contains the list of servers you want to copy files/folders to
$computers = get-content -Path $KfxComputers
# the folder you want to copy to the servers in the $computer variable
$sourceRoot = #("\\wdevkofx110\Kofax Software\Oracle Clients",
"\\wdevkofx110\Kofax Software\Kofax Capture 11")
# the destination location you want the file/folder(s) to be copied to
$destinationRoot = "C$\temp"
foreach ($computer in $computers) {
$testpath = Test-Path -Path \\$computer\$destinationRoot
if (!$testpath)
{
Write-Host "creating folder and copying files..." -ForegroundColor green
New-Item -ItemType Directory -Force -Path "\\$computer\$destinationRoot"
copy-item -Path $sourceRoot -Recurse -Destination
"\\$computer\$destinationRoot" -Container
} else {
Write-Host "$computer\$destinationRoot folder already exists"
}
}`
You can use Else IF
[String] $KfxComputers = "C:\temp\Kofax Apps\servers.txt"
# This file contains the list of servers you want to copy files/folders to
$computers = get-content -Path $KfxComputers
# the folder you want to copy to the servers in the $computer variable
$sourceRoot = #("\\wdevkofx110\Kofax Software\Oracle Clients",
"\\wdevkofx110\Kofax Software\Kofax Capture 11")
# the destination location you want the file/folder(s) to be copied to
$destinationRoot = "C$\temp"
foreach ($computer in $computers) {
$testpath = Test-Path -Path \\$computer\$destinationRoot
if (!$testpath)
{
Write-Host "creating folder and copying files..." -ForegroundColor green
New-Item -ItemType Directory -Force -Path "\\$computer\$destinationRoot"
copy-item -Path $sourceRoot -Destination
"\\$computer\$destinationRoot" -Container -Recurse -force
}
ElseIF ($testpath) {
Write-Host "folder already exists, copying files..." -ForegroundColor green
copy-item -Path $sourceRoot -Destination
"\\$computer\$destinationRoot" -Container -Recurse -force
}
else {
Write-Host "$computer\$destinationRoot folder already exists"
}
}`
I'm trying to copy files to a specific folder based on a file name.
For example:
Current Folder - C:\Stuff\Old Files\
The File- 206.Little Rock.map.pdf
Destination Folder - D:\Cleanup\206\Repository
So basically the leading number on the file (206) is part of the subfolder. The "\Repository" would stay constant. Only the leading number would change.
If the file was 207.Little Rock.map.pdf then the destination folder would be
D:\Cleanup\207\Repository
I started with a code I got from here but I'm not sure how to account for the change in number and how to make it create a folder if the folder doesn't exist. So 206\Repository would probably already exist, but I would need the script to create the folder if it doesn't.
$SourceFolder = "C:\Stuff\Old Files\"
$targetFolder = "D:\Cleanup\"
$numFiles = (Get-ChildItem -Path $SourceFolder -Filter *.pdf).Count
$i=0
clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'
Get-ChildItem -Path $SourceFolder -Filter *.PDF | %{
[System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $Name.Repository(".*","\"))
if(!(Test-Path -Path $destination.Directory )){
New-item -Path $destination.Directory.FullName -ItemType Directory
}
[int]$percent = $i / $numFiles * 100
copy-item -Path $_.FullName -Destination $Destination.FullName
Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
$i++
}
Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;
This should do mostly what you need. You might have to tweak the destination path a bit, but that should be fairly straight forward to figure out. I Highly recommend that use a '-' as the delimiter for your file prefix as opposed to a '.' as this will prevent accidentally moving EVERY FILE in a directory if you happen to execute it in the wrong place.
Also, when you write a script, do create functions to do individual units of work, and then call those functions at the end. It's much easier to modify, and debug that way.
<#
.SYNOPSIS
Moves files from source to destination based on FileName
Creates destination folder if it does not exist.
.DESCIPTION
The script expects files with a prefix defined by a hyphen '-' i.e. 200-<filename>.<ext>.
There is no filename validation in this script; it will *probably* skip files without a prefix.
A folder based on the prefix will be created in the destination.
If your file is name string-cheese.txt then it will be moved to $DestinationIn\string\string-cheese.txt
.PARAMETER SourceIn
Source Path (folder) where your files exist.
.PARAMETER DestinationIn
Target Path (folder) where you want your files to go.
.EXAMPLE
& .\CleanUp-Files.ps1 -SourceIn "C:\Users\User\Documents\Files\" -DestinationIn "C:\Users\User\Documents\Backup\" -Verbose
.NOTES
Author: RepeatDaily
Email: RepeatedDaily#gmail.com
This script is provided as is, and will probably work as intended. Good Luck!
https://stackoverflow.com/questions/50662140/copy-file-based-a-specified-folder-based-on-file-name-create-folder-if-it-doesn
#>
[CmdletBinding()]
param (
[string]$SourceIn,
[string]$DestinationIn
)
function Set-DestinationPath {
param (
[string]$FileName,
[string]$Target
)
[string]$NewParentFolderName = $FileName.SubString(0,$FileName.IndexOf('-'))
[string]$DestinationPath = Join-Path -Path $Target -ChildPath $NewParentFolderName
return $DestinationPath
}
function Create-DestinationPath {
[CmdletBinding()]
param (
[string]$Target
)
if (-not(Test-Path -Path $Target)) {
Try {
New-Item -ItemType Directory -Path $Target | Write-Verbose
}
catch {
Write-Error $Error[0];
}
}
else {
Write-Verbose "$Target exists"
}
}
function Move-MyFiles {
[CmdletBinding()]
param (
[string]$Source,
[string]$Destination
)
[array]$FileList = Get-ChildItem $Source -File | Select-Object -ExpandProperty 'Name'
foreach ($file in $FileList) {
[string]$DestinationPath = Set-DestinationPath -FileName $file -Target $Destination
Create-DestinationPath -Target $DestinationPath
try {
Move-Item -Path (Join-Path -Path $Source -ChildPath $file) -Destination $DestinationPath | Write-Verbose
}
catch {
Write-Warning $Error[0]
}
}
}
Move-MyFiles -Source $SourceIn -Destination $DestinationIn
Here is something you might try. The number for the directory is grabbed from a regex match, "(\d+)\..*.pdf". When you are confident that the correct file copies will be made, remove the -WhatIf from the Copy-Item cmdlet.
I did not try to address the Write-Progress capability. Also, this will only copy .pdf files that begin with digits followed by a FULL STOP (period) character.
I do not fully understand the need for all of the Write-Host and Read-Host usage. It is not very PowerShell. pwshic
$SourceFolder = 'C:/src/t/copymaps'
$targetFolder = 'C:/src/t/copymaps/base'
$i = 0
$numFiles = (
Get-ChildItem -File -Path $SourceFolder -Filter "*.pdf" |
Where-Object -FilterScript { $_.Name -match "(\d+)\..*.pdf" } |
Measure-Object).Count
clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'
Get-ChildItem -File -Path $SourceFolder -Filter "*.pdf" |
Where-Object -FilterScript { $_.Name -match "(\d+)\..*.pdf" } |
ForEach-Object {
$NumberDir = Join-Path -Path $targetFolder -ChildPath $Matches[1]
$NumberDir = Join-Path -Path $NumberDir -ChildPath 'Repository'
if (-not (Test-Path $NumberDir)) {
New-Item -ItemType Directory -Path $NumberDir
}
Copy-Item -Path $_.FullName -Destination $NumberDir -Whatif
$i++
}
Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;