In PowerShell,Move-Item cmdlet doesn't create target folders if they don't exist by default. If you want to move a file to a destination folder that doesn't exist, you will get an error like this:

PS> Move-Item test.txt D:\A\Folder\That\Doesnt\Exist
Move-Item : Could not find a part of the path.
At line:1 char:1
+ Move-Item test.txt D:\A\Folder\That\Doesnt\Exist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Users\Metin....esktop\test.txt:FileInfo) [Move-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

In order to create the destination folder easily, I recommend using New-Item cmdlet before moving your files as in the example below:


New-Item -ItemType File -Path $TargetFilePath -Force
Move-Item -Path test.txt -Destination $TargetFilePath -Force

This way, the target directory will be created prior to moving the file. Force argument on Move-Item cmdlet will force PowerShell to overwrite the newly created blank file.

I hope you like this solution. Follow me on twitter to get more tips like this ;)


Join The Discussion