Home > Mobile >  Move files which contains specific text from subfolders in powershell
Move files which contains specific text from subfolders in powershell

Time:06-17

I am trying to loop through subfolders from one folder (in a directory) with excel files which contain a specific name in the file name and move them to another folder. I have the following code but it doesn't seem to work:

$RootFolder = "C:\Users\files"
$SubFolders = Get-ChildItem -Path $RootFolder -Directory
$TextToFind = 'text'
$DestinationDirectory = 'C:\Users\move_here'
Foreach($SubFolder in $SubFolders)
{ Get-ChildItem -Path $SubFolder -Filter '*.xlsx' -File -Recurse|
where {(Get-Content $_.FullName) -match $TextToFind} |
    Move-Item -Destination $DestinationDirectory }

CodePudding user response:

if I am not mistaken, it should be enough to change the variable in the where to make the move work. Below the script with the modification:

$RootFolder = "C:\Users\files"
$SubFolders = Get-ChildItem -Path $RootFolder -Directory
$TextToFind = 'text'
$DestinationDirectory = 'C:\Users\move_here'
Foreach($SubFolder in $SubFolders)
{ Get-ChildItem -Path $SubFolder -Filter '*.xlsx' -File -Recurse|
where {$Subfolder -match $TextToFind} |
    Move-Item -Destination $DestinationDirectory }

CodePudding user response:

It may be that I don't fuly understand the question, but why not use the -Filter for this instead of a Where-Object clause afterwards?

$RootFolder = "C:\Users\files"
$DestinationDirectory = 'C:\Users\move_here'
$TextToFind = 'text'

$SubFolders = Get-ChildItem -Path $RootFolder -Directory
foreach ($folder in $SubFolders) {
    Get-ChildItem -Path $folder.FullName -Filter "*$TextToFind*.xlsx" -File -Recurse |
    Move-Item -Destination $DestinationDirectory -WhatIf
}

i have added the -WhatIf switch to the Move-Item cmdlet, so when testing nothing actually gets moved. Once you are satisfied that what is shown in the console is OK, remove the -WhatIf safety switch and run again

  • Related