2

I'm using the file system object in Powershell in order to do some folder cycling: let's say having oldFolder, currentFolder and newFolder, this is the process:

  1. DeleteFolder oldFolder
  2. MoveFolder currentFolder to oldFolder
  3. MoveFolder newFolder to currentFolder

When running in script, step 2 or 3 randomly throws CTL_E_PERMISSIONDENIED. When the script stops, I repeat the last command and it finishes correctly.

Seems as if the MoveFolder method works semi asynchronous.

ps: the folders have subfolders and a lot of files

I've tried adding some delay, but I'm not happy not knowing what is happening.

$oldFolder = "D:\test\folder_OLD"
$curFolder = "D:\test\folder"
$newFolder = "D:\test\folder_NEW"

$fso = $fso = New-Object -ComObject scripting.filesystemobject

if (Test-Path $oldFolder) {$fso.DeleteFolder($oldFolder)}

if (Test-Path $curFolder) {$fso.MoveFolder($curFolder,$oldFolder)}

$fso.MoveFolder($newFolder,$curFolder)
Creatyves
  • 21
  • 1
  • 1
    have you tried using pure powershell instead of mixing wscript with PoSh? [*grin*] – Lee_Dailey Apr 02 '19 at 18:01
  • Surprisingly and unfortunately, [directory (folder) removal is inherently asynchronous on Windows](https://serverfault.com/a/942429/176094), which causes intermittent, unpredictable failures. I suspect that's what's happening here; for a robust custom folder-removal function, see https://stackoverflow.com/a/53561052/45375 – mklement0 Apr 02 '19 at 18:06
  • @Lee_Dailey: The problem is ultimately the Windows API, and PowerShell's `Remove-Item -Recurse` is equally affected, as is `cmd.exe`'s `rd /s`. – mklement0 Apr 02 '19 at 18:09
  • @Lee_Dailey, yeah, that it only happens intermittently is part of the problem; apparently there's talk about making the Windows API synchronous soon: https://github.com/dotnet/corefx/issues/33603#issuecomment-466595889 – mklement0 Apr 02 '19 at 18:44

1 Answers1

0

Thanks for the swift responses. That confirms my suspicion.

I'll try to use another method, maybe pure powershell as proposed by Lee.

Creatyves
  • 21
  • 1