2

I am iterating through a directory full of sub directories, looking for the newest file at each level.

The code below does this, but I need to be able to add each line/loop of the iterator to an array so that at the end I can output all the data in tabular format for use in Excel.

Any advice on how I can do this?

    $arr = get-childItem -Path "\\network location\directory" | select FullName
    $res = @()

    foreach($fp  in $arr)
    {

    get-childItem -Path $fp.FullName | sort LastWriteTime | select -last 1 Directory, FullName, Name, LastWriteTime

    }

2 Answers 2

1

Here's a one-liner for you, split onto multiple lines for readability with the backtick escape character. You can copy paste this and it will run as is. The csv file will be created in the folder where you run this from.

dir -rec -directory | `
    foreach {
        dir $_.fullname -file | `
        sort -Descending lastwritetime | `
        select -first 1
    } | `
    export-csv newestfiles.csv

dir is an alias for get-childitem. foreach is an alias for foreach-object. %, gci and ls are even shorter aliases for get-childitem. Note that I am avoiding storing things in arrays, as this is doubling the work required. There is no need to enumerate the folders, and then enumerate the array afterwards as two separate operations.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand you correctly, you just need to pipe the results into $res. So adding | %{$res += $_} should do the trick

  $arr = get-childItem -Path "\\network location\directory" | select FullName
  $res = @()


    foreach($fp  in $arr)
    {

     get-childItem -Path $fp.FullName | sort LastWriteTime | select -last 1 Directory, FullName, Name, LastWriteTime | % {$res += $_}

    }

    $res | % {write-host $_}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.