3

I have a folder containing files, folders, and a target subfolder. I'm trying to move all contents of the folder into the target subfolder (excluding the target subfolder) using Move-Item. When I do so I get an unexpected "does not exist" error for the target subfolder. Am I misusing the command? Is there another argument that achieves what I want?

PS C:\test> dir


    Directory: C:\test


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         6/14/2023   1:06 PM                anotherFolder
d-----         6/14/2023  12:50 PM                subfolder
-a----         6/14/2023  12:50 PM              6 ItemA
-a----         6/14/2023  12:50 PM              6 ItemB
-a----         6/14/2023  12:50 PM              6 ItemC


PS C:\test> Move-Item * -Destination subfolder -Exclude subfolder
Move-Item : Cannot move item because the item at 'C:\test\subfolder' does not exist.
At line:1 char:1
+ Move-Item * -Destination subfolder -Exclude subfolder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand

PS C:\test> dir


    Directory: C:\test


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         6/14/2023  12:50 PM                subfolder

Looks like the move succeeded but I would prefer to not get an error for simple move operation... if I try without the Exclude argument, I get a different error:

PS C:\test> Move-Item * -Destination subfolder
Move-Item : The parameter is incorrect.
At line:1 char:1
+ Move-Item * -Destination subfolder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\test\subfolder:DirectoryInfo) [Move-Item], IOException
    + FullyQualifiedErrorId : MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

PS C:\test>
Simea
  • 33
  • 5

1 Answers1

1

You're seeing a bug in Windows PowerShell, which has been fixed in PowerShell (Core) 7+.

Workaround:

Get-Item * -Exclude subfolder | Move-Item -Destination subfolder

Note: To include hidden files and subfolders, add -Force to the Get-Item call.

  • Get-ChildItem * would work too in this case, but Get-Item * works more predictably across various scenarios.

  • Note that you must use * in order for the -Exclude parameter to work as intended (in other words: just Get-ChildItem -Exclude subfolder would not work), because of the counterintuitive way the -Include and -Exclude parameters are implemented - see this answer for background information.

mklement0
  • 382,024
  • 64
  • 607
  • 775