Move files that contain a string to a subfolder with the same name as the original (PowerShell) -
i'm using powershell , 2 days i'm struggling on issue.
in directory c:\dir_1 have many subfolders (sub_1, sub_2, ..., sub_n). each of them contains several text files. each subfolder i=1,2,...,n, want move text files contain string "my-string" directory c:\dir_2\sub_i.
for example, if file x in path c:\dir1\sub_5 contains string "my-string", want move location c:\dir_2\sub_5. destination folder existing.
i tried several modifications of following code, not work:
get-childitem "c:\dir_1" | where-object {$_.psiscontainer -eq $true} | foreach-object {get-childitem "c:\dir_1\$_" | select-string -pattern "my-string" | group path | select name | %{move-item $_.name "c:\dir_2\$_"}}
so, basically, tried is: foreach subfolder in dir_1, take files contain string , move them subfolder in dir_2 same name. tried several small modifications of code, cannot around mistakes. main error "move-item: given path format not supported"... help?
i feel better first approach
$dir1 = "c:\temp\data\folder1" $dir2 = "c:\temp\data\folder2" $results = get-childitem $dir1 -recurse | select-string -pattern "asdf" $results | foreach-object{ $parentfolder = ($_.path -split "\\")[-2] move-item -path $_.path -destination ([io.path]::combine($dir2,$parentfolder)) }
select-string
can take file paths pipeline input. feed files under $dir1
using -recurse
of children in sub folders. $results
contain array of match objects. 1 of properties path of matched file.
with of $results
go though each , extract parent folder path. combine folder path $dir2
in order move it destination.
there several assumptions taking here. account if need be. mention 1 know issue first.
- your folders should not have other subfolders under "sub_1, sub_2, ..., sub_n" else attempt move incorrectly. can addressed little more string manipulation. in attempt make code terse using
-recurse
created caveat.
Comments
Post a Comment