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
?
CodePudding user response:
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.." }