I have a powershell script that is running the following script that moves my files and folders from the current folder to destination folder successfully. However it shows the error "the process cannot access the file because it is being used by another process"
My script:
mkdir filestobehere
$dest = '.\filestobehere'
Move-Item .\* $dest -Exclude $dest -Force
I am stumped.
I tried to try catch, but it is not being caught and I still get the error.
mkdir filestobehere
Get-ChildItem -Path "./" |
ForEach-Object {
$dest = '.\filestobehere'
Try {
Move-Item .\* $dest -Exclude $dest -Force
}
Catch {
Write-Hose "File is in use"
}
}
CodePudding user response:
As stated in the comments, the primary problem with your attempt is that you're using a path as your -Exclude
argument, which isn't supported.[1]
As a result, the exclusion attempt is ineffective, and Move-Item
attempts to move the filestobehere
subdirectory to itself, which predictably fails (I do see a different error, however).
While using only a file name with -Exclude
fixes the problem with your command in PowerShell (Core) 7 , a bug in Windows PowerShell prevents targeting the excluded name as the (possibly positionally implied) -Destination
argument.
A solution that works in both PowerShell editions:
$dest = 'filestobehere' # OMIT the ".\"
Get-Item .\* -Exclude $dest | Move-Item -Force -Destination $dest
[1] as of PowerShell 7.3.0; however, there are two relevant feature requests: GitHub issue #15159 and GitHub issue #4126.