* PowerShellで,正規表現を使いマッチしたファイルをディレクトリーの階層ごと指定ディレクトリーにコピー

:CATEGORIES: PowerShell,正規表現


cls
$source = "C:\test"
$destination = "C:\test2"
$filter = [regex] "^[0-9]{6}\.(jpg|gif)"

$bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filter) -or ($_.PSIsContainer)}
foreach ($item in $bin) {
Write-Host "

      • -

Obj: $item
Path: "$item.fullname"
Destination: "$item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")
Copy-Item -Path $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")
}

[source:]windowsWindows:ファイル名の正規表現を使用したファイルのコピー/移動? https://www.it-swarm-ja.tech/ja/windows/windows%EF%BC%9A%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D%E3%81%AE%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%9F%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E3%82%B3%E3%83%94%E3%83%BC%E7%A7%BB%E5%8B%95%EF%BC%9F/959356621/

 コピー元とコピー先のディレクトリーを変更して,LinuxUbuntu)のPowerShell Coreで実行。


PS /kk/pwork/tv> $bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filter) -or ($_.PSIsContainer)}
PS /kk/pwork/tv> foreach ($item in $bin) {
>> Write-Host "
>> ----

>> Obj: $item
>> Path: "$item.fullname"
>> Destination: "$item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")
>> Copy-Item -Path $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")

>> }

      • -

Obj: /kk/pwork/tv/2020-09-09_190059_テレビの画面・.jpg
Path: /kk/pwork/tv/2020-09-09_190059_テレビの画面・.jpg
Destination: /home/a66/w3/
(以下略)

 書式を少し変更して実行。


PS /kk/pwork/tv> $filter = [regex] "^[0-9]{4}-09-09_1936.+\.(jpg|gif)"
PS /kk/pwork/tv> $bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filter) -or ($_.PSIsContainer)}
PS /kk/pwork/tv> foreach ($item in $bin) {
>> Write-Host "
>> ----

>> Obj: $item
>> Path: "$item.fullname"
>> Destination: "

>> $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")
>> Copy-Item -Path $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,"")

>> }

      • -

Obj: /kk/pwork/tv/2020-09-09_193623_テレビの画面・.jpg
Path: /kk/pwork/tv/2020-09-09_193623_テレビの画面・.jpg
Destination:
/home/a66/w3/

      • -

Obj: /kk/pwork/tv/2020-09-09_193644_テレビの画面・.jpg
Path: /kk/pwork/tv/2020-09-09_193644_テレビの画面・.jpg
Destination:
/home/a66/w3/

      • -

Obj: /kk/pwork/tv/2020-09-09_193652_テレビの画面・.jpg
Path: /kk/pwork/tv/2020-09-09_193652_テレビの画面・.jpg
Destination:
/home/a66/w3/
PS /kk/pwork/tv>

 「-or ($_.PSIsContainer)」という部分が条件式でのディレクトリー(フォルダ)の指定と思われますが,パスをテキストとしてファイル名を除いて使っているようです。

 やってみると,ページの末尾にある方法を参考に,Linux環境ですが,次の方法でも同じことが出来ました。

dir|?{$_ -match '2020-09-10.*\.(jpg|png)'}|%{cp $_.fullname /home/a66/tmp}