约 2153 字

约 11 分钟

#PowerShell 的 New-Item 命令

New-Item
    [-Path] <String[]>
    [-ItemType <String>]
    [-Value <Object>]
    [-Force]
    [-Credential <PSCredential>]
    [-WhatIf]
    [-Confirm]
    [<CommonParameters>]

功能

创建新项并设置其值;在文件系统中可以创建文件和目录。

类型

Cmdlet,属于 Microsoft.PowerShell.Management。

参数

  • [-Path] <String[]> - 新项的位置;省略时使用当前位置;此参数不解释通配符
  • -Name <String> - 新项名称,相对于 -Path 指定的位置
  • -ItemType <String> - 新项的类型,别名 Type;FileSystem 支持 File、Directory、SymbolicLink、Junction、HardLink
  • -Value <Object> - 新项的初始值,别名 Target;创建链接时表示目标路径
  • -Force - 覆盖只读项,或在路径中自动创建所需目录
  • -Credential <PSCredential> - 指定执行操作的凭据;内置提供程序不支持此参数
  • -WhatIf - 显示将要执行的操作而不实际执行;别名 wi
  • -Confirm - 执行命令前提示确认;别名 cf

#示例

创建文件

> New-Item -Path . -Name 'notes.txt' -ItemType File -Value 'hello'
    Directory: /home/user/project

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2026-11-02 09:00             5 notes.txt
  • -Value 会作为新文件的初始内容写入。

创建目录

> New-Item -Path ./src -ItemType Directory
  • -ItemType Directory 用于创建目录。

一次创建多个文件

> New-Item -ItemType File -Path ./a.txt, ./b.txt
  • -Path 接受字符串数组,因此可以一次创建多个项。

创建符号链接

> New-Item -ItemType SymbolicLink -Path ./current -Target ./releases/1.0.0
  • -Target 是 -Value 的别名,表示链接指向的目标路径。
  • 相对目标路径从 PowerShell 6.2 起受支持。

覆盖已有文件

> New-Item -Path ./notes.txt -ItemType File -Force
  • -Force 会将已存在文件的内容重置为空,而不是抛出错误。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2