PowerShell 5 引入了New-TemporaryFile cmdlet https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-temporaryfile?view=powershell-5.1,这很方便。我怎样才能做同样的事情,但不是创建一个文件而是创建一个目录?有没有New-TemporaryDirectory
cmdlet?
我认为可以通过使用 GUID 作为目录名称来完成此操作,而无需循环:
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
[string] $name = [System.Guid]::NewGuid()
New-Item -ItemType Directory -Path (Join-Path $parent $name)
}
使用 GetRandomFileName 的原始尝试
这是我的港口这个 C# 解决方案 https://stackoverflow.com/a/278457/27581:
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
$name = [System.IO.Path]::GetRandomFileName()
New-Item -ItemType Directory -Path (Join-Path $parent $name)
}
碰撞可能性分析
有多大可能是这样GetRandomFileName
将返回临时文件夹中已存在的名称?
- 文件名以以下形式返回
XXXXXXXX.XXX
其中 X 可以是小写字母或数字。
- 这给了我们 36^11 种组合,按位计算约为 2^56
- 调用生日悖论 https://en.wikipedia.org/wiki/Birthday_problem,一旦我们到达文件夹中的大约 2^28 个项目(大约 3.6 亿),我们预计会发生冲突
-
NTFS 支持文件夹中大约 2^32 个项目 https://technet.microsoft.com/en-us/library/cc781134%28WS.10%29.aspx#w2k3tr_ntfs_how_dhao,因此可以使用以下方式获得碰撞
GetRandomFileName
NewGuid
另一方面可以是 2^122 种可能性之一 https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29,使得碰撞几乎不可能发生。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)