Get-Childitem with millions of files

Hello all,
My task is to create a report with all subfolders in a given path, sorted after the newest LastWriteTime on any file in the folder.
The ultimate reason is to determine which folders have been unused for long enough to move to offline storage.
So far I've come up with this:
Get-ChildItem $folderpath | Where {$_.PsIsContainer} | foreach-object { Get-ChildItem $_ -Recurse -ErrorAction SilentlyContinue | Where {!$_.PsIsContainer} | Select Name,DirectoryName, LastWriteTime, Mode | Sort LastWriteTime -descending | select -first
1}|export-csv $drive:\report.csv
I know this works, I've tested it on a couple of folders.
The problem is that the folder I really want to run the report for contains approximately 6.5 million files in many thousands of subfolders. Memory usage goes through the roof, server gets unresponsive, I have to kill the script before users get angry.
I suppose that PowerShell tries to create an array in memory before actually piping and sorting, and that's the reason for the memory problem.
Is there a smarter way to do it?

It is all on 1 line, everything is going through the pipeline, it has to do each part of the pipeline before it`s gets to the next part of the pipeline.
Do each each folder separately, here is a function to step through a folder structure recursively. Customize it for your needs. The maximum amount of resources used will be limited to one folder.
function Recurse-Folders([string]$path) {
Set-Location -Path $Path
# $L = Get-Location
# Do something at this location
[String[]]$Folders = Get-ChildItem "." -Directory
ForEach ($F in $Folders)
Recurse-Folders($F)
Set-Location -Path ".."

Similar Messages

  • Powershell Get-childItem: The specified path, file name, or both are too long.

    Hey Scriping Guys!
    I've been using a PowerShell script for a couple of years now to generate a monthly report showing the size of user folders on a number of departmental file servers.  It's working just fine on all file servers except one where the users have gotten carried away with creating sub-folders and using realy long descriptive file names.  The problem piece of script is this:
    $colItems = (Get-ChildItem \\192.168.10.5\marketing -recurse | Measure-Object -property length -sum)
    "marketing-serv\marketing: "+"{0:N2}" -f ($colItems.sum / 1GB) + " GB"
    The reply I get is:
    Get-ChildItem : The specified path, file name, or both are too long. The fully
    qualified file name must be less than 260 characters, and the directory name mu
    st be less than 248 characters.
    At G:\data\Server_space_Report\serverspace2.ps1:37 char:27
    + $colItems = (Get-ChildItem  <<<< \\192.168.10.5\marketing -recurse | Measure-Obje
    ct -property length -sum)
    Yes, the message is correct, however, when I connect to the server, right click the folder and chose properties it returns a size of 128 GB.  My questions are
    1. Why does clicking on folder properties not produce an error (what is it doing differently from my script)?
    2. How can I fix my script?
    Thanks,

    I am trying to clear up the older open posts on this forum. If this is still an unresolved issue for you please let me know. If you do not post back within one week I will assume it is resolved and will close this thread.
    Thank you
    Ed Wilson
    Microsoft Scripting Guy

  • Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

    Hi, Im trying to get the whole path in my server, so i tried that with this following code
    Get-ChildItem $sourceFolder  -Recurse | ?{$_.PsIsContainer} |Get-Acl
    But then, it showed me somtehing like this :
    Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
     I tried to find the solver everywhere and mostly they propose to change the path name, which is impossible, since I am working with my company server, and those folder have already there before i start to work here, then the other ask me to use robocopy,
    but all of the trick just dont work
    is there any way to solve this problem? thanks

    There is no simple solution to this. And it is not a limitation of powershell itself, but of the underlying NTFS file system.
    If the problem is that a folder with a name longer than 248 exists anywhere within your directory structure, you are hooped.
    If the problem is that some fully qualified path names exceed 260 characters, then, in those cases, the solution already given is to create a psdrive partway up the path from the drive letter or server/share root of the path. Unfortunately, the output produced
    will be relative to that psdrive and not to what is specified as the $sourcefolder.
    unless you already know where those problematic paths are, you might consider trying to trap those errors and have your script figure out where it needs to create psdrives. You might then be able to calculate the equivalent path for each file or folder and
    output that. the programming effort would be simpler to just created a psdrive for each folder encountered, however I expect that would be very inefficient.
    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

  • SMTP folder, "Badmail" is getting flooded with millions of junk emails- SharePoint 2010 incoming email

    Hi All,
    Need your expert advice and help !
    Incoming e-mail has been successfully configured and working fine on SharePoint 2010.
    Issue: Badmail folder is getting flooded with millions of junk emails. First Queue folder gets them, and then moves them to Badmail folder. Incoming Email has been successfully configured for SharePoint 2010 and SharePoint list is receiving the emails (there
    is a delay, but that is fine!)
    Please help. what other information should i provide to help understand this issue better ?
    Naveed.DG MCITP, MCTS -SharePoint 2010 Administrator "Vote As Helpful" If it helps!!

    What Reverse DNS Lookup does is attempt to validate that the piece of mail came from an IP that belongs to the domain in the EHLO/HELO command - http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/233c0fde-7315-479a-a7fb-2e9d00ff73fd.mspx?mfr=true
    So it doesn't directly filter spam (certainly possible to get spam from GMail/Hotmail servers that Reverse DNS Lookup will see as 'valid').
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Get-ChildItem with -LiteralPath is throwing "The specified wildcard character pattern is not valid" when filenames contain brackets

    I'm trying to get a list of folders in a hierarchy that don't contain any mp3 files. (The goal here is to eventually clean up all the "empty" folders that only have album art, thumbs.db, desktop.ini, etc. files left). So I wrote a quick PowerShell
    command to try to do this. But it doesn't seem to be working.
    I already checked out this thread <Get-ChildItem
    SomeFile[].txt occurs error because of the [brackets]: "specified wildcard pattern not valid"> and I think I'm using LiteralPath correctly. Any other hints for troubleshooting this problem? Here's the command I'm using.
    Get-ChildItem -Recurse -Directory | ?{
    @( @(Get-ChildItem -LiteralPath $_.FullName -Recurse) | ?{
    $_.Extension -eq ".mp3"}).Count -eq 0 }
    This is on the latest version of PowerShell found in Windows Technical Preview.

    Fair enough, but it still doesn't answer the original question- why isn't this working with -LiteralPath when the path contains brackets? 
    Get-ChildItem -Recurse -Directory | ?{
    @( @(Get-ChildItem -LiteralPath $_.FullName -Recurse) | ?{
    $_.Extension -eq ".mp3"}).Count -eq 0 }
    Thanks,
    Ben

  • Get-Childitem with Get-FileHash Info

    Hello,
    I have been able run the following script to get File names in a Recurse folders, although I'm looking to use Get-Filehast too, although I'm not sure or unable to tag this on the end of this script File-filehast info.  could you advise.
    my current Get-Childitem script
    get-childitem'\\folder1\folder2\folder3'-recurse|
    Add-Member
    -MemberTypeScriptProperty-NameVersion-Value{
    $this
    .VersionInfo.ProductVersion
    -PassThru|
    select-object
    DirectoryName,Name,Version,LastWriteTime,Length|where{
    $_.DirectoryName
    -ne$NULL}

    Hi I'm outputting to a text file, which I'm then importing into a database, although I have the following objects
    of which I looking to get also hash (Algorithm SHA256) file values as well.  Thanks
    ( DirectoryName,Name,Version,LastWriteTime,Length
    my code is this & screen print from PowerShell
    get-childitem'\\ServerShare\Folder1\Folder2\FolderData'-recurse|
    Add-Member
    -MemberTypeScriptProperty-NameVersion-Value{
    $this
    .VersionInfo.ProductVersion
    -PassThru|
    select-object
    DirectoryName,Name,Version,LastWriteTime,Length|where{
    $_.DirectoryName
    -ne$NULL}
    |Export-Csv-PathC:\folder0\data1.txt
     

  • How do you get audio with your .avi files?

    I'm trying to do a project that has some .avi files but there isn't any audio. Is there a way to get it?

    There's a free downloadable program called Streamclip (www.squared5.com/) that will let you convert the audio format to .aiff audio that can be played by iMovie. I had a clip that wouldn't play audio in iMovie, and Streamclip was able to convert it so it would play.

  • Powershell get-childitem UnauthorizedAccessException

    I am running the Get-ChildItem -recurse command against files on a remote file server and am getting an error that I can't explain (see below).  The account running the command has full control of all of the directories listed in the tree and can open/edit
    any file via Windows explorer.  The account in question (domain\_myservice_account) is a domain account and it can successfully run the command on my laptop or a different server.  This command started failing about 1.5 months ago but had worked
    successfully from that server for 2 years.
    The command fails whether I try using the UNC name or a mapped drive to the directory.  It seems to successfully scan dir7 through dir12 with no issues the error comes once it reaches directory dir13 and it's children.
    Is there some configuration that I need to change on the servers where this command is failing in order to get this working again?
    Please help as I have been trying to figure this out for a while now with no progress.
    Thanks,
    Mike
    Get-ChildItem : Access to the path '\\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11\dir12\dir13' is denied.
    At line:1 char:14
    + Get-ChildItem <<<<  \\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\ -recurse -filter my_file_*.gz
        + CategoryInfo          : PermissionDenied: (\\Server...\dir12\dir13:String) [Get-ChildItem], UnauthorizedAccessException
        + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

    Thank you for your response.  For clarity I have run the same command from my local PC (as myself or the service account that the process has run under for 2 years) and it works fine.  However when I run the command from my Windows 2008 R2 Server
    I get the issue I mentioned above.  I know this it is not a permissions issue because of this testing.
    I tried running the command you mentioned above and it appears that the process fails when it fails at dir12 and never makes it to any of the child directories beyond that point.  The process works fine up through dir11.
    Works fine at this level
    \\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11
    Fails for all at this level
    \\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11\dir12
    Let me know if you have any other ideas.

  • CM-ImportDriver and Get-ChildItem

    I am trying to use the CM-ImportDriver Cmdlet and running into a problem.  After I import the module, I change my site to ABC1:.  From there, I cannot use Get-ChildItem for a UNC path and the CM-ImportDriver throws an error saying it needs a valid
    driver to import.  That happens because it cannot access the UNC path from earlier.  If I change back to C:, then I can run Get-ChildItem with no problem.  What do I need to do in order to bridge the gap between using C: and ABC1:? 
    The CM-ImportDriver requires a UNC path to pull the stored drivers from, which is fine. However, I cannot get it to read the UNC paths provided.   Thanks in advance. 
    Best, Jacob I'm a PC.

    Hi,
    This is taken from here Get-ChildItem - In its basic form the Get-ChildItem cmdlet provides functionality similar to the dir command. For example, if you simply type Get-ChildItem
    at the Windows PowerShell prompt you’ll get back information about the objects in the current location.
    For example this lists HKLM registry child items
    Set-Location HKLM:
    Get-ChildItem
    For example this lists C:\ drive child items
    Set-Location C:\
    Get-ChildItem
    For example in CM 2012 R2 it lists all the admin console nodes
    Set-Location PS1:\
    Get-ChildItem
    You need to query the driver sources before you change the connection context to your site code. For example like this
    #Step 1
    Set-Location C:\
    $Drivers = Get-childitem -path "\\cm01\Sources\OSD\Drivers\Sources\Lenovo\W7x64\T500" -Recurse -Filter "*.inf"
    #Step 2
    Set-Location PS1:\
    foreach($item in $Drivers)
    Import-CMDriver -UncFileLocation $item.FullName
    Best,
    Kaido

  • Using get -childitem to scan different drives but append one text file.

    Folks,
    I need some help, I wrote the below to scan for certain files types on client machines but I cant get the script to scan anything other than the C$. Apologies I am kind of new to scripting and PS. The script is kicked off using a batch file that makes the
    CR directory on the clients. I think the problem stems from the $disk variable or the way I have used foreach or the loop - any help would be appreciated
    Set-Location c:\
    $s = new-object -comObject SAPI.SPVoice
    $s.speak("Scan in progress")
    write-host "Scanning for files"
    $Extension = @("*.zip","*.rar","*.ppt","*.pdf")
    $Path = "$env:userprofile\Desktop"
    $disks = "c$","D$"
    foreach ($disks in $disks)
    {get-childitem -force -include $Extension -recurs -EA SilentlyContinue >$path\files.txt}
    $s.speak("Scan completed")
    Write-Host "Scan complete, files.txt created on your desktop - press any key to exit..."
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
    Remove-Item c:\cr -recurse -EA SilentlyContinue
    exit

    Then there is "$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")" , What are you trying to do?
    It looks like that is a pause after the code has completed to give the user time to read the message prior to exiting.
    @V Sharma - As gaff-jakobs has mentioned, there are some parts of your code that need looked at. Please take a look at what he has advised and make the necessary changes. If you want to append data (doing a > does not append), I would look at using Out-File
    -Append -FilePath <filename> to accomplish this. 
    Usually, outputting to a text file limits what you can do with the output once it goes to a text file. I would look at using something such as Export-Csv -Append -Path instead (assuming you are running PowerShell V3). But if saving to a text file is part
    of your requirement, then just be sure to use the first method I mentioned.
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • I am in the middle of a job using CS 6, but at the same time opening the Creative Suite apps.  I created an InDesign file in CS 6, saved it, and now I can't open it. I'm getting this message: Cannot open file because it was saved with a newer version of A

    I am in the middle of a job using CS 6, but at the same time opening the Creative Suite apps.  I created an InDesign file in CS 6, saved it, and now I can't open it. I'm getting this message: Cannot open file because it was saved with a newer version of Adobe InDesign CC (10.1). You must use that version or later to open the file." AARRGGHH! So how do I access the file?

    Sounds like you opened and saved it in CC, so now you need to go back to CC and either complete the project there, or export to IDML to take it back into CS6.

  • I am trying to get help with WMPlayer tech support Adobe Reader cant open wmpsupport.htm files why?

    i am trying to get help with WMPlayer tech support Adobe Reader cant open wmpsupport.htm files why?

    Adobe Reader opens PDF files, nothing else.

  • I downloaded an update for my Safari web browser to "snow leopard". When I click on the .dmg file, a window opens up with a .pkg file but when I click on the .pkg file I get a prompt saying that it doesn't know what program to open it with. with a

    I downloaded an update for my Safari web browser to "snow leopard". When I click on the .dmg file, a window opens up with a .pkg file but when I click on the .pkg file I get a prompt saying that it doesn't know what program to open it with.

    I suspect if you're trying to open a file in 08 that's been opened in 09 the file has been updated to 09 and will not open in 08.

  • When I open Firefox (with Google as home page), I get prompted to save a file (application/octet-stream)

    This is my mother's computer. It's an HP Pro something. It has Win 7 Pro and Firefox is up to date. I'm not sure when this started because she doesn't use it every day. We can't get to Google at all using Firefox. I even tried a new tab just now and I get prompted to save a file (earlier the file it is prompting to save is NFRC_FLE13007-1A-RD_3300_SN_CIG_IS20_i89.pdf [the two dashes might be underscores - can't read my own writing!] Now it doesn't show me the file name). I tried using bing to search for this file name and didn't get any results.
    I already tried clearing the cache and also resetting the browser using CTRL-F5. I've rebooted after that too. No changes...
    I have not cleared cookies - I think she relies on a lot of them and I don't want to get her more confused!
    Also, I've set up a number of "shortcuts" on her desktop so she can go directly to some websites. One is for Yahoo, one is for WebMD, etc. When I click on these, I do not have the issue. Seems to be related only to Google. Okay, just tried Google Maps and the same thing happens... And same thing happens with GMail. I captured the window, see the attachments..
    Thanks!
    p.s. I occasionally (on my computer) get prompted to save a file in Firefox when I hit the back button. I just say cancel and then do it again and everything is fine. I don't know if this is related either. I have Win 8.1 on a Lenovo laptop.

    Try to boot the computer in [http://windows.microsoft.com/en-us/windows/start-computer-safe-mode#start-computer-safe-mode=windows-7 Windows Safe Mode with network support] (press F8 on the boot screen) open firefox and see if that happens again.

  • How can I get the size of a file with apple script

    I try to get the size of a file within an apple script. But I did not find information how to do this.

    There are two ways. I think Apple is moving toward using System Events, which is listed first.tell application "Finder"
    set myFile to selection as alias
    --this just gets a file for me to work with
    --coercing it into an alias is required for the other functions
    end tell
    tell application "System Events"
    get size of myFile
    end tell
    set myInfo to (info for myFile)
    get size of myInfo

Maybe you are looking for

  • How can i print a scrit to keep in wait for some time then be printed

    Hi Experts, This is sheela reddy.I am new to SDN. I need your help. as per my requirement there is a trasaction code .let say X. So when i excute X and save the data through the Tcode,then it automtically calls script and given for printing Since the

  • How do I get my contacts and pictures back after getting another Iphone?

    I just got another Iphone4 from apple today as my older one got broken. After I plugged in my Iphone it did the whole back up thing but all of my contacts and my photos have been erased from my Iphone. I'm wondering how I'm able to get them all back.

  • Pre-fill the filename in Fileupload UI

    Hi, I am unable to pre-fill the filename in fileupoad UI. When I launch the WD app, on the browser it get the following URL http://devai063.private.xxxx.com:8081/sap/bc/webdynpro/sap/zgi_file_upload?sap-language=EN at the end I add &filename=c:benefi

  • Franchisee POS Sales rebate accrued against vendor

    Hi, Following requirement from the client: Generate rebate settlement for a Vendor based on POS sales made by Retail stores. Proposed standard SAP solution: 1. Create for each vendor master record a customer master record. And assign the customer mas

  • Theme won't install from Device Manager.

    I downloaded a theme for my Curve 8310 and it shows it downloaded in  the device manager but when I try to open it it does nothing.  How do I install this?  Thanks.