File transfer from one folder to another - powershell

I was wondering if anyone can help me with this problem, of moving files from C: drive to a network drive.
So at work we have a machine that outputs .txt files. For example these files include data about pets, so in the folder I have hundreds of files that are named similar to dogs_123456_10062019.txt then cats_123457_10062019.txt.
Now the first number is a reference number than changes per .txt file that is created and the other is a date, as said I can have hundreds of these per day the reference and date is not important to the transfer as the file includes all this information anyway
Now I have a network folder structure of Y:dogs & Y:cats and wanted a automated script that transfers all dog & cat text files to the corresponding network drive.
The network drive name cannot be changed as it's used by a monitoring software that outputs graphs based on the information in the text file.
Is this possible? Hopefully I've explained myself
Cheers

If folder names match file names then you can do something like that:
$SourceFolderPath = "C:\Source\"
$DestinationFolderPath = "Y:"
$FileList = Get-ChildItem -Path $SourceFolderPath
foreach($File in $FileList){
$FolderName = ($File.Name | Select-String -Pattern ".+?(?=_)").Matches.Value
$File | Move-Item -Destination "$DestinationFolderPath\$FolderName"
}
If names of folders do not match file names, you would need to manually create a dictionary of what should go where and then translate those
The code above is obviously not an enterprise level stuff :)

Related

How to search for a specific file name then move all files after that file to another folder using PowerShell

Let's say I have 10 PDF files in a folder named c:\Temp
1440_021662_54268396_1.pdf
1440_028116_19126420_1.pdf
1440_028116_19676803_1.pdf
1440_028116_19697944_1.pdf
1440_028116_19948492_1.pdf
1440_028116_19977334_1.pdf
1440_028116_20500866_1.pdf
1440_028116_20562027_1.pdf
1440_028116_20566871_1.pdf
1440_028116_20573350_1.pdf
In my search, I know I am looking for a file that will match a specific number, for example 19676803 (I'm getting the number to search for from a SQL Query I'm running in my script)
I know how to find that specific file, but what I need to be able to do is move all the files after the searched file has been found to another pre-defined folder. So using the 10 PDFs above as the example files, I need to move all the files "after" the file named 1440_028116_19676803_1.pdf to another folder. I know how to move files using PowerShell, just do not know how to do it after/from a specific file name. Hope that makes sense.
$batchNumCompleted = 'c:\Temp\'
$lastLoanPrinted = $nameQuery.LoanNumber
$fileIndex = Get-ChildItem -path $batchNumCompleted | where {$_.name -match $lastLoanPrinted}
Can anyone provide suggestions/help on accomplishing my goal? I'm not able to provide all code written so far as it contains confidential information. Thank you.
Use the .Where() extension method in SkipUntil mode:
$allFiles = Get-ChildItem -path $batchNumCompleted
$filesToMove = $allFiles.Where({$_.Name -like '*19676803_1.pdf'}, 'SkipUntil') |Select -Skip 1
Remove the Select -Skip 1 command if you want to move the file with 19676803 in the name as well

how to check if file with same name but with different extension exists in a directory Powershell

I am trying to find two things here. I have thousands of files in a folder. lets take example of one file and We can apply same logic to all files
If file with same name but with different extension exists.
If it exists, I need to compare the lastwritetime or the timestamp to find out which file is newer.
For example, if I have a file culture.txt I supposed to have a corresponding file culture.log.
If I have culture.txt but culture.log file is missing, then its an issue, so I want to output names of all .txt file for which corresponding .log files are missing.
If both culture.txt and culture.log are available, then I want to check if the culture.txt was generated after culture.log. If culture.txt is generated before culture.log, there is an issue so, I need to output the names of such .txt files with this issue saying "Culture.txt was generated before culture.log- Please rerun the program".
Anyone who can help would be appreciated. Thank You.
A little more help needed on same question if I can get. The code suggested by Esperento is completely working fine but the requirement is updated. In a folder, I have multiple files with multiple extensions and not limited to just .txt and .log. I can have .doc, .docx, .xls and many other files in the same folder.
Now about updated requirement. I have to look for file names with 3 specific extensions only. One of them is program file. Which should be generated first obviously. Let’s say Culture.prog. then when I run the Culture.Prog two files will be generated like culture.log first and culture.txt respectively.
So obviously, the timestamp on prog is older than log and timestamp on log is older than txt which generated very last.
We have to check the availability of 2 corresponding files(log and prog) in reference to .txt file only which is generated last.
So, first check is, if 2 corresponding files are available for .txt file. Next check is the timestamp is corresponding for these 3 files in order. We have to output only if one of the condition is not satisfied, otherwise its ok if we don’t output anything. For example, if for culture.txt, if .log or .prog file is missing we have to output the fact that which or both files are missing. If the time stamp of txt file is older than log and/or prog we have to output that fact. I hope I am clear in my request. Thank you
try this:
#list file and group by name without extension
Get-ChildItem "C:\temp\test" -file -filter "*.*" | group Basename |
%{
$group= $_.group
# if not same name, missing message
if ($_.Count -eq 1)
{
"'{0}' are missing" -f $group.Name
}
#else search into current group file with great creation time and print message
else
{
$group | % {$file=$_; $group | %{if ($_.CreationTime -gt $file.CreationTime) {"'{0}' has beeen generated before '{1} " -f $file.Name, $_.Name} } }
}
} | out-file "C:\temp\test\result.txt"

Windows file search within a search, how? App, script, GREP, powershell, notepad hack?

I am trying to search for folders created within a certain date range, then search for files with certain attributes in only those folders. I thought with Windows 8's "advanced query system" this would be a 2 minute job...it isn't!
Can anyone recommend an easy way to do this? I'm thinking along the lines of regular expressions i can input into AstroGrep, or a Notepad++ hack, as it's easy to copy folder paths from windows search into a text document.
Thanks!
EDIT: To clarify, I am trying to find files which were added to the system during a certain date range. Searching by file created/modified attributes does not help as these attributes are carried over when the file is moved. However a folder's date attributes do change when files are moved in and out. Therefore I need to search for folders by date, then (because of the huge number of files and subfolders) search within the resulting folders for my files.
You could use the Get-ChildItem cmldet to retrieve all directories during a certain date range (for example: Now and a Month ago):
$dateNow = Get-Date
$dateaMonthAgo = $dateNow.AddMonths(-1)
$directories = Get-ChildItem -Path 'C:\' -Directory -Recurse |
Where { $_.LastAccessTime -le $dateNow -and $_.LastAccessTime -ge $dateaMonthAgo }
Now you have all directories that matches the date range. You can iterate over them and search for your files:
$directories | Get-ChildItem -Filter 'yourFile.txt'

Powershell script to move files based on a source list (.txt

I have thousands of files in a directory (.pdf, .xls, .doc) and they all have a similar naming convention (the "type" is always a constant string, ie: billing or invoice);
accountname_accountnumber_type.pdf
accountname_ accountnumber_type.doc
accountname_accountnumber_type.xls
The task at hand is to receive a random list of accountnames and account numbers (the "type" is always a constant, ie: billing, invoice, shipping or order and they vary in format) and move them from Directory A into Directory B. I can get the list into a .csv file to match the accountname_accountnumber_type.
I have been trying to create a powershell script to reference the accountname_accountnumber and move those items from one directory A to directory B with no luck.
SAMPLE I found something a bit simpler, but I wanted to be able to edit this to create a new destination and not halt if the file is not found from this list. Also, if I could have this pick from a .txt list I think that would be easier than pasting everything.
$src_dir = "C:\DirA\"
$dst_dir = "D:\DirB-mm-dd-yyyy\" #This code requires the destination dir to already be there and I need to have the code output a new Directory, it could output based on date script run that would be amazing
$file_list = "accountname1_accountnumber001_type", #If I can select to import csv here
"accountname2_accountnumber002_type",
"accountname3_accountnumber003_type",
"accountname4_accountnumber004_type",
"accountname5_accountnumber005_type",
"accountname6_accountnumber006_type"
foreach ($file in $file_list) #This errors out and stops the script if the file is not located in source and I need to have the script continue and move on, with hopefully an error output
{
move-Item $src_dir$file $dst_dir
}
They can be any file format, I am trying to get the code to match ONLY the accountname and accountnumber since those two will define the exact customer. Whether it is invoice, billing or shipping doesn't matter since they want all files associated with that customer moved.
For Example there could be 4 of each for every account and the type format may vary from pdf, doc and xls, I need to move all files based on their first two indicators (accountname,accountnumber).
alice_001_invoice.pdf
alice_001_billing.doc
alice_001_shipping.pdf
alice_001_order.xls
George_245_invoice.pdf
George_245_billing.doc
George_245_shipping.pdf
George_245_order.xls
Bob_876_invoice.pdf
Bob_876_billing.doc
Bob_876_shipping.pdf
Bob_876_order.xls
Horman_482_invoice.pdf
Horman_482_billing.doc
Horman_482_shipping.pdf
Horman_482_order.xls
CSV:
accountname,accountnumber
Alice,001
George,245
Bob,876
Horman,482
How about this :
$CurrentDate = [DateTime]::Now.ToString("MM-dd-yyyy")
$DestinationDir = "D:\DirB-$CurrentDate"
New-Item $DestinationDir -ItemType Directory -ErrorAction SilentlyContinue
$AccountToMove = Import-CSV $CSVPath
Foreach ( $Account In $AccountToMove ){
$FilePattern = "*$($Account.AccountName)*$($Account.AccountNumber)*"
ls $SourceDir | Where Name -like $FilePattern | Move-Item -Destination $DestinationDir
}
The code part - you already edited off from the post - about moving files to subdirectories doesn't make much sense with your business rules. As you never show the sample CSV file contents, it's all guessing.
For easier processing, assume you got the following source files. Edit your post to show the CSV file contents and where you would like to move the files.
C:\some\path\A\Alice_001_bill.doc
C:\some\path\A\Alice_001_invoice.xls
C:\some\path\A\Bob_002_invoice.pdf
C:\some\path\A\Bob_002_invoice.doc
C:\some\path\A\Eve_003_bill.xls
C:\some\path\A\Eve_003_invoice.doc

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
}
}