none
Powershell Copy Folder if it contains a Specific File - Conditional RRS feed

  • Question

  • Hello Powershell friends,

    I am trying to see if this is possible.

    If a Folder contains a txt file called Copy.txt

    Copy that Folder to a destination.


    The below is a brief sketch of the idea, is this possible?

    =================
    $source = "C:\Users\PW\Desktop\Source"

    $dirs =  dir C:\Users\PW\Desktop\Destination  -Recurse| Where {$_.psIsContainer -eq $true} |


    if ( Folder Contains a File Called Copy.txt)
    {
        "Copy this Folder"
    }
    else
    {
        "Do Not Copy Folder"
    }


    $dirs | foreach-object {Copy $source $_.fullname}
    =========================

    How do i fix this thank you :)
    Thursday, May 19, 2016 2:17 PM

Answers

  • $source='C:\NewFolder'
    $destination='C:\NewFolder1'
    if($location=Get-ChildItem $source -Name copy.txt -File -Recurse)
    {
     $source=$source+"\"+$location.Split("\")[0]
     Copy-Item $source -Destination $destination -Recurse -Force
    }

    • Marked as answer by Dan_CS Thursday, May 19, 2016 5:37 PM
    Thursday, May 19, 2016 4:25 PM

All replies

  • Hi,

    Sure, you can do that. This will be helpful:

    http://ss64.com/ps/test-path.html


    Thursday, May 19, 2016 2:41 PM
  • Besides Mike's way, you can also use Get-ChildItem to accomplish the above.

    $source='C:\NewFolder'
    $destination='C:\NewFolder1'
    if(Get-ChildItem $source -Name copy.txt -File -Recurse)
    {
     Copy-Item $source -Destination $destination -Recurse -Force
    }

    Thursday, May 19, 2016 3:05 PM
  • Thank you for the Replies, Mike & Mukesh

    Mukesh your code works good  to copy the whole folder directory.

    I put  copy.txt into a subfolder

    If I just wanted to copy that subfolder  - what would i have to add or remove.

    if ( -Not Get-ChildItem $source -Name copy.txt -File -Recurse)

    the above does not work

    thank you :)

    Thursday, May 19, 2016 4:09 PM
  • $source='C:\NewFolder'
    $destination='C:\NewFolder1'
    if($location=Get-ChildItem $source -Name copy.txt -File -Recurse)
    {
     $source=$source+"\"+$location.Split("\")[0]
     Copy-Item $source -Destination $destination -Recurse -Force
    }

    • Marked as answer by Dan_CS Thursday, May 19, 2016 5:37 PM
    Thursday, May 19, 2016 4:25 PM
  • Mukesh,

    thank you very very much :)

    it worked splendidly. I did research for hours on google - but nothing worked.

    It seems simple but its not if you dont know how to do this.

    Cheers for your kind help

    Best regards

    :) 

    Thursday, May 19, 2016 5:36 PM
  • Welcome :)
    Thursday, May 19, 2016 5:38 PM