Powershell Foreach循环不循环遍历每个目录

时间:2018-04-05 19:24:51

标签: powershell loops foreach directory

我正在编写一个遍历目录中每个特定文件夹的脚本,通过CreationTime对build_info *文件进行排序,从每个目录中获取最新的文件并将其分配给唯一的变量。我有排序部分工作,但问题是我的循环没有通过每个目录,它只是从第一个获得结果并将其放入多个唯一变量。

所以,这就是我想要的:

servers01 most recent build_info*.txt file --> $servers01

servers02 most recent build_info*.txt file --> $servers02

servers03 most recent build_info*.txt file --> $servers03

但这就是它实际上在做的事情:

servers01 most recent build_info*.txt file --> $servers01

servers01 most recent build_info*.txt file --> $servers02

servers01 most recent build_info*.txt file --> $servers03

这是我到目前为止的代码:

$Directory = dir D:\Files\servers* | ?{$_.PSISContainer};
$Version = @();
$count = 0;

foreach ($d in $Directory) {
    $count++
    $Version = Select-String -Path D:\Files\servers*\build_info*.txt -Pattern "Version: " | Sort-Object CreationTime | Select-Object -ExpandProperty Line -Last 1;
    New-Variable -Name "servers0$count" -Value $Version -Force
}

我需要更改什么才能确保循环遍历每个路径并将该路径的文件分配给其各自的变量?

1 个答案:

答案 0 :(得分:3)

您循环遍历目录数,但由于变量$d未在循环中使用,因此您实际上并未遍历目录。

尝试此操作,添加Write-Host即可获得一些反馈。

$Directory = dir D:\Files\servers* | ?{$_.PSISContainer};
$Version = @();
$count = 0;

foreach ($d in $Directory) {
    $count++
    Write-Host "Working on directory $($d.FullName)..."

    $latestFile = Get-ChildItem -Path "$($d.FullName)\build_info*.txt" | Sort-Object CreationTime -Descending | Select-Object -First 1      
    $Version    = Select-String -Path $latestFile.FullName -Pattern "Version: " | Select-Object -ExpandProperty Line -Last 1;

    New-Variable -Name "servers0$count" -Value $Version -Force

}