简体   繁体   中英

Powershell List Excel Files and Copy

I apologize for the naivety of this post, please forgive my newness.

I have approximately 20,000 network files to filter through and copy certain ones to a local drive.

File List Requirements:

  • Excel files of various type (.xls, .xlsx, .xlsm)

  • Only files modified after 4/1/2022

  • Only files that contain "2022" in the filename

If the file meets those requirements then:

  • Copy the file to a local folder (original folder path structure doesn't matter, all files can go in one folder)

  • Output the original path and filename to a txt file, along with the lastwritedate

I have created the following code, which successfully obtains all excel files and creates the filename list

Get-ChildItem "D:\network_folder\" -Filter *.xls -Recurse | Select-Object -Property FullName, LastWriteTime |
    Export-Csv -Path "C:\local_folder\file_list.csv" -Force -NoTypeInformation

However I cannot figure out the following issues:

  • how and where to filter for the lastwritetime

  • how and where to filter for the "2022" in the name

  • how and where to copy the files to the local folder

  • right now I'm just putting this all in the command line, do I need to make some file to run this process?

Thank you for any assistance you can provide!

I guess you want something like this. It searches for files in the source folder with 2022 in the name and having.xls (or anything following xls) as extension.

It then loops over these items, creates the subfolder structure where they were found in the destination folder, copies the files and finally writes out a CSV file with information of the original file.

$sourcePath  = 'D:\network_folder'
$destination = 'D:\dest_folder'
$refDate     = [datetime]::new(2022,4,2)  # --> next day date as of midnight

Get-ChildItem -Path $sourcePath -Filter '*2022*.xls*' -File -Recurse |
    Where-Object {$_.LastWriteTime -ge $refDate} | ForEach-Object {
        # create the destination folder if it does not already exist
        $target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourcePath.Length)
        $null = New-Item -Path $target -ItemType Directory -Force
        # copy the file
        $_ | Copy-Item -Destination $target
        # output the wanted properties from the original file
        $_ | Select-Object Name, FullName, LastWriteTime
    } | Export-Csv -Path "C:\local_folder\file_list.csv" -Force -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM