我用谷歌搜索了以下问题,但找不到任何答案。 有人可以帮我解决这个问题吗? 通过 Windows Powershell 创建新文件的命令是什么?
我猜您正在尝试创建一个文本文件?
New-Item c:\scripts\new_file.txt -type file
其中“C:\scripts ew_file.txt”是完全限定的路径,包括文件名和扩展名。
使用 echo 创建文件
echo some-text > filename.txt
示例:
C:\>echo This is a sample text file > sample.txt
C:\>type sample.txt
This is a sample text file
C:\>
使用 fsutil 创建文件
fsutil file createnew filename number_of_bytes
示例:
fsutil file createnew sample2.txt 2000
File C:\sample2.txt is created
C:\data>dir
01/23/2016 09:34 PM 2,000 sample2.txt
C:\data>
限制
Fsutil 只能由管理员使用。对于非管理员用户,它会抛出以下错误。
c:\>fsutil file /?
FSUTIL 实用程序要求您具有管理权限。 c:>
希望这有帮助!
street smart(快速,肮脏但有效):(可能会更改文件并添加一个不可见的字符,这可能会导致编译器失败)
$null > file.txt
$null > file.html
课本方法:
New-Item -path <path to the destination file> -type file
示例:
New-Item -path "c:\" -type file -name "somefile.txt"
或
ni file.xt -type file
缺少 -path 参数意味着它在当前工作目录中创建它
ni filename.txt
将
filename.txt
替换为您的文件。
我发现这是该问题的最简单答案,请参阅其他答案以了解更多详细信息。
这是在 Powershell 中创建空白文本文件的另一种方法,它允许您指定编码。
第一个例子
对于空白文本文件:
Out-File C:\filename.txt -encoding ascii
如果没有
-encoding ascii
,Powershell 默认为 Unicode。如果您希望其他来源可以读取或编辑它,则必须指定 ascii
。
用新文本覆盖文件:
"Some Text on first line" | Out-File C:\filename1.txt -encoding ascii
这会将
filename.txt
中的任何文本替换为 Some Text on first line.
将文本附加到当前文件内容:
"Some More Text after the old text" | Out-File C:\filename1.txt -encoding ascii -Append
指定
-Append
会单独保留 filename.txt
的当前内容,并将 Some More Text after the old text
添加到文件末尾,保持当前内容不变。
正如许多人已经指出的那样,您可以使用
New-File
命令创建文件。ni
,但如果您习惯使用 unix 命令,您可以轻松创建自己的自定义命令。
创建一个
touch
命令来充当 New-File
,如下所示:
Set-Alias -Name touch -Value New-Item
这个新别名将允许您创建新文件,如下所示:
touch filename.txt
这将使这 3 个命令等效:
New-Item filename.txt
ni filename.txt
touch filename.txt
请记住,为了使其持久化,您应该将别名添加到您的 powershell 配置文件中。要获取它的位置,只需在 ps 上运行
$profile
即可。如果您想直接编辑它,请运行 code $profile
(对于 VSCode)、vim $profile
(对于 vim)或其他命令。
另一种方法(我喜欢的方法)
New-Item -ItemType file -Value 'This is just a test file' -Path C:\Users\Rick\Desktop\test.txt
来源:新项目
使用 New-item cmdlet 和您的新文件名。
New-item <filename>
示例:
New-item My_newFile.txt
# encodings:
New-Item file.js -ItemType File -Value "some content" # UTF-8
"some content" | Out-File main.js -Encoding utf8 # UTF-8-BOM
echo "some content" > file.js # UCS-2 LE BOM
任何命令行中最简单的方法:
"" > path/to/file/filename.extension