Get file which is closest to a given date - powershell

I need a script which will get me the file which is closest to a given date, and need some help please.
For example:
$GivenDate = [datetime]"06/26/2017 10:30"
Get-ChildItem $backupDirectory -Filter "*.diff"
Output looks like this:
Mode LastWriteTime Length Name
-a---- 25.06.2017 15:30 506368 db1_backup_2017_06_25_153001_5520722.diff
-a---- 26.06.2017 7:30 1597952 db1_backup_2017_06_26_073001_6387310.diff
-a---- 26.06.2017 9:30 675840 db1_backup_2017_06_26_093001_6217913.diff
-a---- 26.06.2017 11:30 657408 db1_backup_2017_06_26_113001_1234104.diff
-a---- 26.06.2017 13:30 675328 db1_backup_2017_06_26_133000_9901392.diff
-a---- 26.06.2017 15:30 673792 db1_backup_2017_06_26_153001_5430241.diff
How can I select the file that is closest to to $givenDate?

Calculate a TimeSpan between the LastWriteTime property value and your $GivenDate, then sort on the absolute value (the duration) of the timespan:
$Closest = Get-ChildItem $backupDirectory -Filter *.diff |Sort {(New-TimeSpan $GivenDate $_.LastWriteTime).Duration()} |Select -First 1

variation of #Mathias R. Jessen solution (duration and timespan are not necessary)
Get-ChildItem $backupDirectory -file -Filter *.diff | sort {($GivenDate - $_.LastWriteTime)} | Select -First 1

Related

I want to import a csv to use as filter in the powershels gci command

I have a csv file with extension and description.
I want to import that file and use it as the filter parameter in a gci command.
But I get no results.
I expect to get a list of the jpg files but get no results.
$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv
#$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv -header extension
$extensions.extension
$src = "c:\scripts\"
#gci c:\scripts\ -Include $Extensions.extension #-Force -recurse
#gci c:\scripts\ -filter $Extensions.extension #-Force -recurse
gci c:\scripts\|where{$_ -like $extensions.extension}`
my csv file looks like this (just made a small file for testing)
extension,"description"
*.JPEG,JPEG Image
*.JPF,JPEG 2000 Image
*.JPG,JPEG Image
*.JPG_LARGE,Twitter Large JPEG Image
There are jpg files in that folder :
Directory: C:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 23/11/2022 11:02 509592 nieuw9754560_02-10.jpg
-a--- 23/11/2022 11:02 576486 nieuw9754560_02-15.jpg
-a--- 23/11/2022 11:02 641802 nieuw9754560_02-20.jpg
-a--- 23/11/2022 11:01 705702 nieuw9754560_02-25.jpg
-a--- 23/11/2022 11:01 763249 nieuw9754560_02-30.jpg
I've just tested this - I think all you're missing is changing the $_ to $_.Extension for the Get-ChildItem, on the last line.
Hope that helps.
Doesn't directly fix the code but here's another way of getting the result using foreach to iterate through each extension in the array:
foreach($e in $extensions.extension) {
gci c:\scripts\ | where {$_ -like $e}
}

How can I rename files by prepending a sequence number to the original file names?

guys does anyone know how can i do this? I am trying to list some files in a numerical order by adding 1, 2, 3 and so on to the beginning of the file names while also keeping the files' original names.
Here are the codes i tried
$nr = 1
Dir -path C:\x\y\deneme | %{Rename-Item $_ -NewName (‘{0} $_.Name.txt’ -f $nr++ )}
dir | select name
This code just orders the files like 1, 2, 3... Without keeping the original names.
$n = 1
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace $_.Name ,'{0} $_.Name' -f $n++}
This one did not work like i thought.
Try the following, which renames all .txt files in the current dir. by prepending a sequence number to them:
$n = 1
Get-ChildItem *.txt |
Rename-Item -WhatIf -NewName { '{0} {1}' -f ([ref] $n).Value++, $_.Name }
Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.
The ([ref] $n).Value++ trick makes up for the fact that delay-bind script blocks run in a child scope of the caller, where the caller's variables are seen, but applying ++ (or assigning a value) creates a transient, local copy of the variable (see this answer for an overview of PowerShell's scoping rules).
[ref] $n in effect returns a reference to the caller's variable object, whose .Value property can then be updated.
As for what you tried:
'{0} $_.Name.txt', as a single-quoted string, is interpreted verbatim by PowerShell; you cannot embed variable references in such strings; for that you need double-quoting ("...", and you'd also need $(...) in order to embed an expression such as $_.Name) - see the bottom section of this answer for an overview of PowerShell's string literals.
So yeah, I agree with #Abraham, I don't see a scenario where you can rename the files but also retain the original files without copying them :)
This should do the trick:
$i = 0; Get-ChildItem x:\path\to\files | ForEach-Object {
$i++
$destPath = Join-Path $_.DirectoryName -ChildPath "$i $($_.Name)"
Copy-Item -Path $_.FullName -Destination $destPath
}
Example:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 6/24/2021 7:08 PM 2 1 testfile0.txt
-a---- 6/24/2021 7:08 PM 2 2 testfile1.txt
-a---- 6/24/2021 7:08 PM 2 3 testfile2.txt
-a---- 6/24/2021 7:08 PM 2 4 testfile3.txt
-a---- 6/24/2021 7:08 PM 2 5 testfile4.txt
-a---- 6/24/2021 7:08 PM 2 testfile0.txt
-a---- 6/24/2021 7:08 PM 2 testfile1.txt
-a---- 6/24/2021 7:08 PM 2 testfile2.txt
-a---- 6/24/2021 7:08 PM 2 testfile3.txt
-a---- 6/24/2021 7:08 PM 2 testfile4.txt

move files by names (variable last letter) to folder

We have a systeem at work where we change the last letter of the name of a file if we make a new version. We change it alphabetic and O is the firstone and then A,B,C,...
But the older versions don't need to stay in that folder any more. I am looking for a "simpel" solution in powershell to move this older files to a folder "old".
I don't know how to start in powershell (except to move to the right folder) and don't know if it is possible.
Any suggestions can help.
Set-Location -Path "Z:\PDF\2018\18-00190 StBV THV Depret Franki\2D"
Get-ChildItem | Sort-Object -Property name
In PowerShell you tend to work a lot with pipelines, creating sequences of objects and filtering, projecting or otherwise manipulating them along the way. Your problem could be solved as follows in a few steps (whether they're simple or not remains to be seen, but your requirements necessitate some custom code):
First group all files by their base file name without the suffix
Get-ChildItem -File | Group-Object { $_.Basename -creplace '_[A-O](?=$|\.)' }
This creates a grouping key which is basically the file name without the last-changed suffix. Then we have for each group all revisions that have been created for that file. E.g. for your file names 1409-EM-M-PL-7000_A.dwg.pdf you'd get a group named 1409-EM-M-PL-7000.dwg.pdf containing all versions of that file.
I'm assuming here that no letter beyond O will actually be used, but you can adapt the regex if necessary.
Sort the revisions in order:
ForEach-Object {
$_.Group | Sort-Object { $_.Basename -creplace '_O(?=$|\.)', '_0' } -Descending
}
We replace the _O temporarily with _0 for sorting here to get the correct order since it's the oldest but would usually appear as the latest version.
We also sort descending here (so we get the latest versions first) to make the next step easier, since we actually want to grab the files we have to move, not those we want to retain.
Retain the latest n versions by grabbing every file except the latest 3 in this case:
Select-Object -Skip 3
Move the remaining files to old:
Move-Item -Destination old
Putting it all together:
Get-ChildItem -File |
Group-Object { $_.Basename -creplace '_[A-O](?=$|\.)' } |
ForEach-Object {
$_.Group |
Sort-Object { $_.Basename -creplace '_O(?=$|\.)', '_0' } -Descending |
Select-Object -Skip 3
} |
Move-Item -Destination old
Stick a -WhatIf on the MoveItem to see what's being done without actually changing anything. As an example:
H:\Stuff\54664753> ls
Directory: H:\Stuff\54664753
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2019-02-13 10:10 1 old
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_A.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_B.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_C.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_D.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_O.dwg.pdf
-a---- 2019-02-13 10:11 0 file2_A.pdf
-a---- 2019-02-13 10:11 0 file2_O.pdf
-a---- 2019-02-13 10:11 0 file3_O.xml
-a---- 2019-02-13 10:11 0 file_A.txt
-a---- 2019-02-13 10:11 0 file_B.txt
-a---- 2019-02-13 10:11 0 file_C.txt
-a---- 2019-02-13 10:11 0 file_O.txt
H:\Stuff\54664753> Get-ChildItem |
>>> Group-Object { $_.Basename -creplace '_[A-O](?=$|\.)' } |
>>> ForEach-Object {
>>> $_.Group |
>>> Sort-Object { $_.Basename -creplace '_O(?=$|\.)', '_0' } -Descending |
>>> Select-Object -Skip 2
>>> } |
>>> Move-Item -Destination old -Whatif
What if: Performing the operation "Move File" on target "Item: H:\Stuff\54664753\1409-EM-M-PL-7000_B.dwg.pdf Destination: H:\Stuff\54664753\old\1409-EM-M-PL-7000_B.dwg.pdf".
What if: Performing the operation "Move File" on target "Item: H:\Stuff\54664753\1409-EM-M-PL-7000_A.dwg.pdf Destination: H:\Stuff\54664753\old\1409-EM-M-PL-7000_A.dwg.pdf".
What if: Performing the operation "Move File" on target "Item: H:\Stuff\54664753\1409-EM-M-PL-7000_O.dwg.pdf Destination: H:\Stuff\54664753\old\1409-EM-M-PL-7000_O.dwg.pdf".
What if: Performing the operation "Move File" on target "Item: H:\Stuff\54664753\file_A.txt Destination: H:\Stuff\54664753\old\file_A.txt".
What if: Performing the operation "Move File" on target "Item: H:\Stuff\54664753\file_O.txt Destination: H:\Stuff\54664753\old\file_O.txt".
You can also try out the individual steps by shortening the pipeline appropriately, e.g. only the initial grouping:
H:\Stuff\54664753> Get-ChildItem |
>>> Group-Object { $_.Basename -creplace '_[A-O](?=$|\.)' }
Count Name Group
----- ---- -----
1 old {old}
5 1409-EM-M-PL-7000.dwg {1409-EM-M-PL-7000_A.dwg.pdf, 1409-EM-M-PL-7000_B.dwg.pdf, 1409-EM-M-PL-7000_C.dwg.pdf, 1409-EM-M-PL-7000_D.dwg.pdf...}
2 file2 {file2_A.pdf, file2_O.pdf}
1 file3 {file3_O.xml}
4 file {file_A.txt, file_B.txt, file_C.txt, file_O.txt}
Or grouping and sorting, but not the rest:
H:\Stuff\54664753> Get-ChildItem -File |
>>> Group-Object { $_.Basename -creplace '_[A-O](?=$|\.)' } |
>>> ForEach-Object {
>>> $_.Group |
>>> Sort-Object { $_.Basename -creplace '_O(?=$|\.)', '_0' } -Descending
>>> }
Directory: H:\Stuff\54664753
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_D.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_C.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_B.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_A.dwg.pdf
-a---- 2019-02-13 10:02 0 1409-EM-M-PL-7000_O.dwg.pdf
-a---- 2019-02-13 10:11 0 file2_A.pdf
-a---- 2019-02-13 10:11 0 file2_O.pdf
-a---- 2019-02-13 10:11 0 file3_O.xml
-a---- 2019-02-13 10:11 0 file_C.txt
-a---- 2019-02-13 10:11 0 file_B.txt
-a---- 2019-02-13 10:11 0 file_A.txt
-a---- 2019-02-13 10:11 0 file_O.txt

Finding a file that has highest number in the filename using powershell

Sorry guys..I am new to powershell. Would be great if someone help with the following scenario:
I have couple of files in a folder c:\test
sample.x.x.1
sample.x.x.2
sample.x.x.3
sample.x.x.4
sample.x.x.5
I want to find the name of the file which has the highest number in its name in the given folder. In the above example, 5 is the highest number and the script should return the output filename as sample.x.x.5
Thanks in advance!
Sorting file names with numbers is quite a problem, as there are two ways. The first one sets them to alphabetical order. That is, 0, 1, 11, 111, 2,... The second one uses natural order. That is, 0, 1, 2, 11, 111.... This is surprisingly tricky and about every third programmer is confused with this.
There's a good answer already, which I'll refer like so,
# Create files 1..5
for($i=1;$i -le 5; ++$i) { set-content sample.x.x.$i -Value $null }
# Tricksy! Create file .10 to confuse asciibetic/natural sorting
set-content sample.x.x.10 -Value $null
ls # Let's see the files
Directory: C:\temp\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2015-09-28 10:29 0 sample.x.x.1
-a---- 2015-09-28 10:29 0 sample.x.x.10
-a---- 2015-09-28 10:29 0 sample.x.x.2
-a---- 2015-09-28 10:29 0 sample.x.x.3
-a---- 2015-09-28 10:29 0 sample.x.x.4
-a---- 2015-09-28 10:29 0 sample.x.x.5
# Define helper as per linked answer
$ToNatural = { [regex]::Replace($_, '\d+$', { $args[0].Value.PadLeft(20,"0") }) }
# Sort with helper and check the output is natural result
gci | sort $ToNatural -Descending | select -First 1
Directory: C:\temp\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2015-09-28 10:29 0 sample.x.x.10
Alphabetical sorting.
PS C:\Users\Gebb> #("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") | sort
sample.x.x.1
sample.x.x.11
sample.x.x.5
Numerical sorting.
PS C:\Users\Gebb> #("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
sort -Property #{Expression={[Int32]($_ -split '\.' | select -Last 1)}}
sample.x.x.1
sample.x.x.5
sample.x.x.11
Largest number.
PS C:\Users\Gebb> #("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
sort -Property #{Expression={[Int32]($_ -split '\.' | select -Last 1)}} |
select -Last 1
sample.x.x.11

Delete oldest versions of a directory in PowerShell

I have a list of directories which are formatted like version numbers and would like to find the N oldest directories and delete them. For example:
/1.2.3.4
/1.2.3.5
/1.2.3.6
I've tried a few things, but I can't quite seem to get where I need to go.
My first try was this:
ls directory | sort Name | select -first 5 | rm -r
However I'm not sure this is going to work in all circumstances, because this will (I presume) do a natural sort. Is that always going to return the correct results?
My next thought was that I could use System.Version to do my sorting. So I ended up with this:
ls directory | %{[System.Version]$_.Name } | sort | select -first 5 | ???
The problem is that I'm not sure how to tie the directory result to the sorting... What's the best way to do this?
gci \\directory produces
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 12/19/2011 5:19 PM 1.0.1052.54849
d---- 12/19/2011 5:29 PM 1.0.1053.54850
d---- 12/19/2011 5:36 PM 1.0.1054.54851
d---- 12/20/2011 2:11 PM 1.0.1056.54875
d---- 12/12/2011 10:39 AM 1.0.991.54625
d---- 12/12/2011 12:08 PM 1.0.992.54627
d---- 12/12/2011 12:22 PM 1.0.993.54628
d---- 12/12/2011 1:15 PM 1.0.994.54630
d---- 12/12/2011 2:45 PM 1.0.996.54636
d---- 12/12/2011 3:34 PM 1.0.997.54640
d---- 12/12/2011 3:48 PM 1.0.998.54641
gci \\directory | Sort-Object { $_Name -as [Version] } produces
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 12/12/2011 1:15 PM 1.0.994.54630
d---- 12/12/2011 12:22 PM 1.0.993.54628
d---- 12/12/2011 2:45 PM 1.0.996.54636
d---- 12/12/2011 3:48 PM 1.0.998.54641
d---- 12/12/2011 3:34 PM 1.0.997.54640
d---- 12/12/2011 12:08 PM 1.0.992.54627
d---- 12/19/2011 5:29 PM 1.0.1053.54850
d---- 12/19/2011 5:19 PM 1.0.1052.54849
d---- 12/19/2011 5:36 PM 1.0.1054.54851
d---- 12/12/2011 10:39 AM 1.0.991.54625
d---- 12/20/2011 2:11 PM 1.0.1056.54875
Does it matter that this is a network share? I'm confused as to why this isn't working... I did a quick sanity check and doing Array.Sort on versions I've created in a unit test are sorted correctly.
You can actually sort on an expression, which will keep your original objects.
Get-ChildItem $path |
Sort-Object { $_.Name -as [Version] } |
Select-Object -Last 1 |
Remove-Item
Will do the trick.
Hope this helps,
Natural sort is the order that you want. 1,2,3..10,11..instead of 1,10,11,2,3..
1..11 | %{$_.tostring()} | sort
Gives it in "ASCIIbetical" order, which is not the natural order we expect it to be in.
Based on what you were doing with version, I would say you can do like this, though it might be a bit over board:
gci directory | %{new-object psobject -p #{version=[version]($_.name);dir=$_ }} |
sort version | select -expand dir -first 5 | rm -r -whatif
or
gci directory | select #{e={[version] $_.name};l="version"}, #{e={$_};l="dir"} |
sort version | select -expand dir -first 5 | rm -r -whatif