访问数组中的元素

时间:2017-10-24 20:14:53

标签: arrays powershell foreach

我遇到了我想要理解的数组循环问题。

我有一个Array变量,用于存储某些目录的路径。

$collectorDirArray1 = @(Get-ChildItem -Path D:\APPS\Server* -Filter Data -Recurse -Directory).Fullname

$collectorDirArray1会返回此信息:

D:\Apps\Server
D:\Apps\Server1
D:\Apps\Server2

foreach遍历$collectorDirArray1并获取3分钟或更长时间的所有* .dat文件。

foreach ($file in $collectorDirArray1) {
    $oldDats = @(Get-ChildItem -Path $collectorDirArray1 -Recurse -Filter "*.dat") | Where {$_.LastWriteTime -lt (get-date).AddMinutes(-3)}
}

$oldDats会返回此信息:

    Directory: D:\APPS\Server\data

Mode                LastWriteTime     Length Name

-a---        2017-10-23   2:40 PM         18 test1.dat

    Directory: D:\APPS\Server2\data


Mode                LastWriteTime     Length Name

-a---        2017-10-17   4:22 PM         17 test2.dat

foreach循环获取LastWriteTime数组中每个文件的$oldDats,并将输出发送到Write-Host

foreach ($element in $oldDats) {
    $FileDate = $element.LastWriteTime
    Write-Host "The files that are 3 minutes old are: $oldDats the LastWriteTime is: $FileDate"
}

返回:

The files that are 3 minutes old are: test1.dat test2.dat the LastWriteTime is: 10/23/2017 14:40:21
The files that are 3 minutes old are: test1.dat test2.dat the LastWriteTime is: 10/17/2017 16:22:03

我在期待

The files that are 3 minutes old are: test1.dat the Last Write time is: 10/23/2017 14:40:21
The files that are 3 minutes old are: test2.dat the Last Write time is: 10/17/2017 16:22:03

如果我直接访问数组中的每个元素($oldDats[0]$oldDats[1]),它会单独返回每个文件名。

为什么变量$oldDats同时包含两个文件名(test1.dat和test2.dat)而不是一个(test1.dat)?

3 个答案:

答案 0 :(得分:2)

你看起来错误地在你的ForEach循环中调用“OldDats”而不是“Element”。代码应如下所示:

ForEach ($element in $oldDats){

    $FileDate = $element.LastWriteTime
    write-host "The files that are 3 minutes old are: $element the 
LastWriteTime is: $FileDate"}

当你运行ForEach循环时,$ oldDats指的是整个数组,其中$ element指的是数组中循环的单个项。希望有所帮助!

答案 1 :(得分:0)

您指的是数组而不是预期的元素。

所有这一切都可以简化:

$Collection = Get-ChildItem -Path 'D:\APPS\Server*' -Filter '*.dat' -Recurse |
                Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-3) } |
                ForEach-Object {
                  Write-Host 'This file is older than 3 minutes: {0}' -f $_.FullName
                  Write-Host 'The LastWriteTime is: {0}' -f $_.LastWriteTime
                  Return $_.FullName
                }

在命令结束时,您的数组将存储在$Collection

答案 2 :(得分:0)

试试这个:

$maxdate=(get-date).AddMinutes(-3)
$Startdir="c:\temp"

Get-ChildItem $Startdir -file -Recurse -Filter "*.dat" | 
    where {$_.Directory -like "$Startdir\server*\data" -and $_.LastWriteTime -lt $maxdate} |
        %{"The files that are 3 minutes old are: {0} the Last Write time is: {1}" -f $_.Name, $_.LastWriteTime}