Tafarel Chicotti
Tafarel Chicotti

Reputation: 163

Get-ChildItem -Recurse don't work recursive

I'm trying create a powershell script to handle files from a directory, but when try use -recurse param, I move entire folder instead only files.

    # where $source = C:\Files
    # and my folder 'Files' have two subfolders '001' and '002' with files inside
    Get-ChildItem -Path $source -Recurse -Filter * |
    ForEach-Object {

        # Get the current date
        $date = (Get-Date).ToString();

        # Add to log file
        Add-Content -Path $log " $date - The file $_ was moved from $source to $target";

        # Show on cmdlet
        Write-Host " $date - O arquivo $_ foi transferido de $source para $target";

        # Move items
        Move-Item $_.FullName $target;
    }

When I try this command Get-ChildItem -Path $source -Recurse ... on cmdlet, works right.

help-me please

Upvotes: 2

Views: 1596

Answers (1)

briantist
briantist

Reputation: 47792

As EBGreen pointed out, you are enumerating folders and files. To filter it in version 2, you'd do something like this:

Get-ChildItem -Path $source -Recurse -Filter * | 
Where-Object { -not $_.PSIsContainer } |
    ForEach-Object {

        # Get the current date
        $date = (Get-Date).ToString();

        # Add to log file
        Add-Content -Path $log " $date - The file $_ was moved from $source to $target";

        # Show on cmdlet
        Write-Host " $date - O arquivo $_ foi transferido de $source para $target";

        # Move items
        Move-Item $_.FullName $target;
    }

The .PSIsContainer property returns true when the item is a container (a folder) as opposed to a leaf (a file).

In PowerShell v3 and higher you could just do:

Get-ChildItem -Path $Source -Directory -Recurse -Filter *

Upvotes: 3

Related Questions