且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PowerShell中创建一个临时目录?

更新时间:2023-11-23 08:38:34

我认为可以通过使用GUID作为目录名而无需循环来完成此操作:

I think it can be done without looping by using a GUID for the directory name:

function New-TemporaryDirectory {
    $parent = [System.IO.Path]::GetTempPath()
    [string] $name = [System.Guid]::NewGuid()
    New-Item -ItemType Directory -Path (Join-Path $parent $name)
}

使用GetRandomFileName的原始尝试

这是我的此C#解决方案的端口:

function New-TemporaryDirectory {
    $parent = [System.IO.Path]::GetTempPath()
    $name = [System.IO.Path]::GetRandomFileName()
    New-Item -ItemType Directory -Path (Join-Path $parent $name)
}

碰撞可能性分析

GetRandomFileName返回临时文件夹中已经存在的名称的可能性有多大?

Analysis Of Possibility Of Collision

How likely is it that GetRandomFileName will return a name that already exists in the temp folder?

  • 文件名以XXXXXXXX.XXX的形式返回,其中X可以是小写字母或数字.
  • 这给了我们36 ^ 11种组合,以位为单位大约为2 ^ 56
  • 调用生日悖论,我们预计到2点左右会发生碰撞.文件夹中有28个项目,大约为3.6亿个
  • NTFS支持以下项中的2 ^ 32项文件夹,因此可以使用GetRandomFileName
  • 发生冲突
  • Filenames are returned in the form XXXXXXXX.XXX where X can be either a lowercase letter or digit.
  • That gives us 36^11 combinations, which in bits is around 2^56
  • Invoking the birthday paradox, we'd expect a collision once we got to around 2^28 items in the folder, which is about 360 million
  • NTFS supports about 2^32 items in a folder, so it is possible to get a collision using GetRandomFileName

NewGuid 可能是2 ^ 122种可能性之一,几乎不可能发生碰撞.

NewGuid on the other hand can be one of 2^122 possibilities, making collisions all but impossible.