none
txt file problem

    Question

  • Hi everyone,

    I have a problem with my school project for powershell. I must order images based on the month and count them. After that I must put the result of the count in a txt file. But here is the problem. I ordered my images and counted them but I can't put the result into a txt file. Basically in the txt file must come the result of the count for each folder. I have already tried with out-file, add-content and >>, but nothing seems to work. Hopefully one of you can help me with this.

    Here is my code:

    function sort-images
    {
    $Source = "C:\Users\user1\Pictures\memes"
    $Destination = "C:\Users\user1\Desktop\Gesorteerdefoto's"

    Get-ChildItem $Source | foreach {
    $Folder = Get-Date $_.LastWriteTime -Format MM-yyyy
    $Folder = $Destination + "\" + $Folder
    if (!(Test-Path $Folder)) {New-Item $Folder -ItemType Directory}
    Copy-Item $_.FullName -Destination $Folder -Container


    }
    Get-ChildItem "C:\Users\user1\Desktop\Gesorteerdefoto's" |  ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count }
    }

    Thank you for your answer!

    Sorry if my English isn't that great it isn't my main language :)

    Friday, May 24, 2019 12:02 PM

All replies

  • Please format your code as code using the code posting tool provided on the icon bar of the post editor (second to last icon). Thanks.

    I would split your task into 2 steps like this:

    $Source = "C:\Users\user1\Pictures\memes"
    $DestinationRoot = "C:\Users\user1\Desktop\Gesorteerdefoto's"
    
    Get-ChildItem -Path $Source |
        ForEach-Object {
            $Month = Get-Date $_.LastWriteTime -Format yyyy-MM
            $Destination = Join-Path -Path $DestinationRoot -ChildPath $Month
            if(-not (Test-Path -Path $Destination)){
                New-Item -Path $Destination -ItemType Directory
            }
            Move-Item -Path $_.FullName -Destination $Destination
        }
    
    Get-ChildItem -Path $DestinationRoot -Recurse -Directory |
        ForEach-Object {
            $FileList = Get-ChildItem -Path $_.FullName -File
            [PSCustomObject]@{
                Folder = $_.FullName
                FileCount = $FileList.Count
            }
        }
    (untested)  ...  Of course you can pipe the result of the second script block to Export-CSV or Out-File just as you like. You should always read the complete help including the examples for all cmdlets you're about to use to learn how to use them.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Friday, May 24, 2019 1:55 PM