如何使用 PowerShell 脚本在目录中查找最新文件?
问题描述:
例如,如果我有一个包含以下文件的目录:
If, for example, I have a directory which contains the following files:
Test-20120626-1023.txt
Test-20120626-0710.txt
Test-20120626-2202.txt
Test-20120626-1915.txt
Test-20120626-1142.txt
如您所见,每个文件名都包含创建时间,并采用可排序的格式.
As you can see, each file name contains the time of creation which is in a sortable format.
如何找到最新的文件名(在本例中为 Test-20120626-2202.txt
)并将其存储在变量中?
How do I find the name of the latest file name (in this case Test-20120626-2202.txt
) and store it in variable?
注意:如果目录路径有任何不同,它也会存储在一个变量中.
答
你可以试试这样的:
$dir = "C:\test_code"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name