1

我正在编写一个 PowerShell 脚本,我需要在其中创建一个目录C:\Users

我的脚本位于桌面上。

我创建目录的脚本是这样的:

New-Item -ItemType "directory" -Force -Path "C:Users\username\scripts\documents"

而是创建目录:

C:\Users\username\Desktop\Users\username\scripts\documents

如何直接在中创建新目录C:\Users

4

1 回答 1

3

\在路径根(驱动器号)后缺少反斜杠:

New-Item -ItemType "directory" -Force -Path "C:\Users\username\scripts\documents"

另请参阅:https ://docs.microsoft.com/en-us/dotnet/api/system.io.path.ispathrooted?view=net-5.0

根路径是固定到特定驱动器或 UNC 路径的文件路径;它与相对于当前驱动器或工作目录的路径形成对比。例如,在 Windows 系统上,根路径以反斜杠(例如,\Documents)或驱动器号和冒号(例如,C:Documents)开头。

请注意,根路径可以是绝对的(即完全限定的)或相对的。绝对根路径是从驱动器根到特定目录的完全限定路径。相对根路径指定驱动器,但其完全限定路径是针对当前目录解析的。以下示例说明了差异。

$relative1 = "C:Documents"
$relative2 = "\Documents"
$absolute = "C:\Documents"

foreach ($p in $relative1,$relative2,$absolute) {
    "'$p' is Rooted: {0}" -f [System.IO.Path]::IsPathRooted($p)
    "Full path of '$p' is: {0}" -f [System.IO.Path]::GetFullPath($p)
}

(我没有[System.IO.Path]::IsPathFullyQualified()在链接的示例中包含调用,因为它不包含在 Windows PowerShell 5.1 中)

于 2021-11-07T16:43:42.900 回答