如何使用regex文件夹将项目复制到目标



我想复制文件夹中的文件,同时匹配类似*-user的正则表达式模式(例如目录名:v52 user(如何使用Copy-Item执行此操作?

如前所述,您可以在Get-ChildItem(无正则表达式(上使用-Filter参数,如下所示:

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

如果你真的想使用regex,你可以做:

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

根据我收集到的您的评论,您需要找到一个文件夹,该文件夹与*-user模式匹配,并且一旦找到该文件夹,您就知道需要复制哪个文件。

为此你可以做:

$fileToCopy  = 'X:somewhereknown_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.." }

或者使用正则表达式:

$fileToCopy  = 'X:somewhereknown_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.." }

最新更新