PowerShell to find and copy a file with wildcard

~OSD~ 2,126 Reputation points
2020-11-26T12:39:49.933+00:00

Hi,

I need to copy a file which is located under a dynamically created subdirectory.

Directory: C:\Users\StandardUser\AppData\Roaming\Mozilla\Firefox\Profiles\dynamically-created-directory\myDesiredFile

$SourceDir ="C:\Users\StandardUser\AppData\Roaming\Mozilla\Firefox\Profiles"
$DestinationDir = "C:\FireFox\"

Wildecard for filter

$FileNameAndExtension = "places.sqlite"

Copy File

Copy-Item $SourceDir $DestinationDir -Filter $FileNameAndExtension -Recurse

Problem: using the above PS settings, I am getting whole PROFILE ddirectory but I want to copy only file as defined in FileNameAndExtension variable ... possible?

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 97,566 Reputation points MVP
    2020-11-26T13:01:27.073+00:00

    Maybe this will work for you (not tested!):

    $SourceDir ="C:\Users\StandardUser\AppData\Roaming\Mozilla\Firefox\Profiles"
    $DestinationDir = "C:\FireFox\"
    $FileNameAndExtension = "places.sqlite"
    Get-Childitem –Path "$SourceDir"  -Include "$FileNameAndExtension" -File -Recurse | Copy-Item  -Destination "$DestinationDir"
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    2 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. ~OSD~ 2,126 Reputation points
    2020-11-27T09:37:57.077+00:00

    Hello again,

    Can I use environment variables such as %UserName%? When I used, the following I am getting error message.

    $SourceDir ="C:\Users\'%UserName%'\AppData\Roaming\Mozilla\Firefox\Profiles"

    Error > Cannot find path 'C:\Users\'%UserName%'\AppData\Roaming\Mozilla\Firefox\Profiles' because it does not exist.

    0 comments No comments

  2. Andreas Baumgarten 97,566 Reputation points MVP
    2020-11-27T10:54:37.593+00:00

    It's possible.

    Please try $env:USERNAME instead of a %username%. This way you get the username of the user that is running the PowerShell script.

    Hope this helps.


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments