【发布时间】:2019-06-27 06:13:26
【问题描述】:
我的目录包含与日期相对应的文件夹(即日期子文件夹)。它们都采用相同的yyyymmdd 格式。此目录中还有其他文件夹,其名称为文本。我想做的是编写一个脚本,让用户输入他们希望看到的前几天。然后该脚本将对每个文件夹执行一些操作。我在弄清楚如何正确获取所有文件夹的列表时遇到了一些麻烦。
目录看起来像:
C:--/
FOO--/
--20190525
--20190526
--20190527
--20190528
--20190529
--20190530
--20190531
--20190601
--20190602
etc.
我目前正在使用for循环,但问题是当月末发生时,即20190531,循环将继续到20190532而不是20190601。
$lastday = (Get-Date).AddDays(-1).ToString("yyyyMMdd")
$lastdayint = [int]$lastday
$days = [Microsoft.VisualBasic.Interaction]::InputBox('How many days back do you want to process?')
if ($days.Length -eq 0) {
Exit
}
$daysint = [int]$days
$firstday = (Get-Date).AddDays(-$daysint).ToString("yyyyMMdd")
$firstdayint = [int]$firstday
for ($i = $firstdayint; $i -le $lastdayint; $i++) {
# Get our dated sub folder by looking through the root of FOO
# and finding the folder that matches the condition
$datedsub = (Get-ChildItem -Path "C:\FOO\*" | Where-Object { ($_.PSIsContainer) -and ($_.Name -eq [string]$i) } ).Name
# If the path does not exist, both processes will fail, so exit out of the loop and move on to the next date
if ( $( try { !(Test-Path -Path ("C:\FOO\$datedsub").Trim() -PathType Container) } catch { $false } ) ) {
Continue
}
}
我有点不知道如何获取名称在两个日期之间的所有文件夹。这在 CMD 脚本中很容易做到,因为一切都是字符串并且文件夹没有属性。但是使用 Powershell 就有点困难了。 脚本需要做的是遍历指定范围内的所有文件夹。我很确定 foreach 循环可能是我最好的选择,但我无法弄清楚如何设置它。
【问题讨论】:
标签: windows powershell