Search code examples
powershellfindmove

Powershell find and move items


Hey there i need to move a lot of files using a powershell script and i kinda need help on this one.

The root is as following

> tree .
\
├───Folder1
│   ├───Sub1
│   │   └───Stockfile
│   └───Sub2
└───Folder2
    ├───Sub1
    │   └───Stockfile
    └───Sub2

The script needs to find the stockfiles and need to move them to the Sub2 folder of each mainfolder.

I made the following script to show all the stockfiles in a list:

$var = get-childitem -Filter *stock* -recurse
foreach ($file in $var) {
write-host ($file.FullName)
}

Solution

  • Try the following:

    Get-ChildItem -File -Recurse -Filter *_stock.csv |
      Move-Item -WhatIf -Destination { $_.FullName -replace '^(.*)\\Sub1\\','$1\Sub2\' }
    

    The approach extracts the path prefix up to ...\Sub1 from the full path of each stock file and makes ...\Sub2 the destination (directory) path.

    That way, stock files are moved from anywhere in the ...\Sub1 subtree directly into ...\Sub2.

    Note:

    • -WhatIf shows you what would happen first; remove it to perform actual moving.

    • The assumption is that the stock file paths contain only one Sub1 component, and that there are no stock files with duplicate names in the Sub1 subtree.

    • -replace interprets its first operand as a regular expression, which is why the \ chars. must be escaped as \\ in order to be recognized as literals; characters in the actual folder name could also require escaping (but don't in this case).

      • If you don't know the folder name in advance, you can safely escape it with [regex]::Escape($folderName)