
[英]Powershell - using dir / GetChildItem to list directories with Date Modified
[英]Powershell GetChildItem using wrong path to find match
现在我正在尝试编写一个小 Powershell 脚本来检查文件是否存在。 我的一个变量称为测试,其目的是在基本路径中查找不超过一天的文件
文件在逻辑中命名为:File2021-02-1717821 等
我现在的代码:
$basepath='C:\Users\MyName\Documents\2020-09-06 193009 Testing'
$date=(get-date).AddDays(-1).ToString("YYYY-MM-dd")
$test=Get-ChildItem $basepath | Where-Object Name -match ($date) | ForEach-Object {$_.FullName}
但是 Test 只会返回脚本位置的文件,而不是 basepath 变量的文件。 我还有一个变量来返回与测试条件匹配的最新文件,但它也返回脚本本身,而不是查看基本路径的目录。
$last = Get-ChildItem -Path $test | Sort-Object LastAccessTime -Descending | Select-Object -First 1
这是你想要做的吗?
($basepath = 'D:\Temp\DateStringFiles')
# Results
<#
D:\Temp\DateStringFiles
#>
($date = (get-date).AddDays(-1).ToString('yyyy-MM-dd'))
# Results
<#
2021-02-16
#>
Get-ChildItem -Path $basepath |
Format-Table -AutoSize
# Results
<#
Directory: D:\Temp\DateStringFiles
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 17-Feb-21 09:07 0 File2021-02-1617821.txt
-a---- 17-Feb-21 09:07 0 File2021-02-1617822.txt
-a---- 17-Feb-21 09:07 0 File2021-02-1717821.txt
#>
(
$test = Get-ChildItem -Path $basepath |
Where-Object -Property FullName -Match $Date |
Format-Table -AutoSize
)
# Results
<#
Directory: D:\Temp\DateStringFiles
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 17-Feb-21 09:07 0 File2021-02-1617821.txt
-a---- 17-Feb-21 09:07 0 File2021-02-1617822.txt
#>
(
$last = Get-ChildItem -Path $basepath |
Where-Object -Property FullName -Match $Date |
Select-Object -First 1 |
Format-Table -AutoSize
)
# Results
<#
Directory: D:\Temp\DateStringFiles
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 17-Feb-21 09:07 0 File2021-02-1617821.txt
#>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.