Create a temporary directory in PowerShell?

前端 未结 8 1720
一生所求
一生所求 2021-02-01 14:36

PowerShell 5 introduces the New-TemporaryFile cmdlet, which is handy. How can I do the same thing but instead of a file create a directory? Is there a New-TemporaryDirec

8条回答
  •  后悔当初
    2021-02-01 15:15

    If you want the looping solution that is guaranteed to be both race- and collision-free, then here it is:

    function New-TemporaryDirectory {
      $parent = [System.IO.Path]::GetTempPath()
      do {
        $name = [System.IO.Path]::GetRandomFileName()
        $item = New-Item -Path $parent -Name $name -ItemType "directory" -ErrorAction SilentlyContinue
      } while (-not $item)
      return $Item.FullName
    }
    

    According to the analysis in Michael Kropat's answer, the vast majority of the time, this will pass only once through the loop. Rarely will it pass twice. Virtually never will it pass three times.

提交回复
热议问题