Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Copy-Item to destination with regex folder?

I want to copy a file in a folder while matching a regex pattern like *-user (example directory name: v52-user)
How can I do this with Copy-Item?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As commented, you can use the -Filter parameter on Get-ChildItem (no regex) like so:

# assuming the file has an extension '.txt'
(Get-ChildItem -Path 'PathWhereTheFileIs' -Filter '*-user.txt' -File) | Copy-Item -Destination 'PathToCopyTo'

If you really want to use regex, you can do:

Get-ChildItem -Path 'PathWhereTheFileIs' -File | 
Where-Object { $_.BaseName -match '-user$' } | 
Copy-Item -Destination 'PathToCopyTo'

From your comments I gather you need to find a folder that matches the *-user pattern and that you know exactly which file you need to copy once the folder is found.

For that you can do:

$fileToCopy  = 'X:\somewhere\known_filename.txt'
$destination = Get-ChildItem -Path 'PathWhereTheFolderShouldBe' -Filter '*-user' -Directory -ErrorAction SilentlyContinue
if ($destination) { Copy-Item -Path $fileToCopy -Destination $destination.FullName }
else { Write-Host "Destination folder could not be found.." }

Or with regex:

$fileToCopy  = 'X:\somewhere\known_filename.txt'
$destination = Get-ChildItem -Path 'PathWhereTheFolderShouldBe' -Directory -ErrorAction SilentlyContinue | 
               Where-Object { $_.Name -match '-user$' }
if ($destination) { Copy-Item -Path $fileToCopy -Destination $destination.FullName }
else { Write-Host "Destination folder could not be found.." }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading