windows - 如何在 Windows 中生成确定大小的文件?

标签 windows scripting file filesystems

最好最快的方法是什么?

最佳答案

PowerShell:

$f = new-object System.IO.FileStream c:\temp\test.dat, Create, ReadWrite
$f.SetLength(42MB)
$f.Close()

这将创建一个包含 42MB 空字节的文件 c:\temp\test.dat。你当然也可以只给出字节数。 (对于 PowerShell,42MB = 42 * 1048576)。

注意:
请记住,除非您指定完整路径(在我的示例中为 C:\temp\test.dat),否则使用 relative 路径(即 .\test.dat)只会在启动 PS 的目录中创建文件,即 ["C:\users\currentUser"] 如果您开始PS 来自 Run... 命令,或者 ["C:\Windows\system32"] 如果您使用 Shift+RightClick (OR) Alt- 启动它>F>S>R 在 Windows 资源管理器上。
要解决此问题,您必须更改底层目录(您可以将其作为 PS 上的命令进行检查: [IO.directory]::GetCurrentDirectory()) 到您在 PS 控制台中所在的当前路径,只需包括以下行:

[IO.directory]::SetCurrentDirectory($(get-location).Path)

因此,总而言之,您可以让它与您当前所在的相对路径一起工作:

[IO.directory]::setCurrentDirectory($(get-location).Path) #Changes directory to current PS directory
[Int64]$size = 150MB #This allows you to set the size beforehand
$f = new-object System.IO.FileStream .\test.dat, Create, ReadWrite
$f.SetLength($size)
$f.Close()

关于windows - 如何在 Windows 中生成确定大小的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808005/

相关文章:

linux - 如何为 Linux、OS X、Windows 制作 Travis CI 测试包?

带有Chrome的Python Selenium,如何下载到具有指定文件名的指定文件夹

python - 获取刚在Python中启动的程序的pid

file - Grails - 从 Quartz 作业和过滤器记录日志

linux - 知道 linux 中的设备特殊文件主要和次要编号

windows - Flutter Desktop - flutter-desktop-embedding 如何将文件保存到硬盘

mysql - 连接mysql,主机ip重定向回本地

php - 要导出的脚本

python - 我们可以将仅包含函数定义的Python文件称为脚本吗?

java - 修改文件名时文件保存失败