Jet string operation
This is my first question here and I am new to powershell.
I have a folder $home\Devoluciones\
with multiple files named DtoXXXYYYYMM.dat where XXX is the company number, YYYY is the current year and MM is the current month.
What I need to do is copy these files to folders with the company name, for example, if I have Dto509201506.dat and Dto908201506.dat I need to copy these files to $destination\509\
and $destination\908\
respectively.
So far, I have the following code:
#List the items and send to a.txt ls $home\Devoluciones\Dto*.dat | select -exp Name > $home\a.txt #From a.txt keep first 6 characters and send to b.txt Get-Content $home\a.txt | foreach {$_.remove(6)} | Add-Content $home\b.txt #From b.txt replace Dto with "" and send to c.txt Get-Content $home\b.txt | foreach {$_ -replace "Dto",""} | Add-Content $home\c.txt #From c.txt copy the files to destination Get-Content $home\c.txt | foreach {copy-item $home\Devoluciones\*$_*.dat $Destination\$_\} #Clean temp files Remove-Item -ErrorAction Ignore $home\a.txt -Force Remove-Item -ErrorAction Ignore $home\b.txt -Force Remove-Item -ErrorAction Ignore $home\c.txt -Force
I would like to achieve the same result by making it "cleaner" than this, I want to learn how to manipulate a string in one line, and if possible, copy everything with just one command.
Thank you, Nestor.
source to share
Here's a simple implementation that should be straightforward. I'm sure someone will add a more concise answer in one line.
$Files = Get-Childitem -path "$home\Devoluciones\*" -include *.dat foreach ($file in $files) { $company = $file.Name.Substring(3,3) copy-item $file.FullName (join-path (join-path $Destination $company) $file.Name) }
EDIT: Fixed bug in destination path
EDIT2: Get-ChildItem "The Include parameter is only valid when the command includes the Recurse parameter or the path leads to a content directory such as C: \ Windows * where a wildcard character is specified."
source to share
All PowerShells can be written as one terrible line if you want it to be, but here's something that's pretty short.
$path = "$home\Devoluciones\" $destination = "C:\temp" Get-ChildItem "$path\dto*.dat" | Copy-Item -Destination {[System.IO.Path]::Combine($destination,($_.Name).Substring(3,3),$_.Name)} -Force
What this will do is exactly what you want. Take all the filtered files and copy each of them to the folder corresponding to the 3-6 letter code contained inside. If the destination folder does not exist, we use -Force
it to create it. Useful for new company codes. We use [System.IO.Path]::Combine
to make the path to the target file, which consists of the destination folder, the company folder and the current file in the pipe.
source to share