我正在研究一个脚本,该脚本将遍历目录中的每个特定文件夹,并按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
}

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

最佳答案

您正在遍历目录的数量,但实际上并没有遍历目录,因为循环中未使用变量$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

}

关于powershell - Powershell Foreach循环未遍历每个目录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49680044/

10-17 03:03