PowerShell New-Item 将创建脚本所在的目录,而不是在指定的路径中

PowerShell New-Item will create the directory where the script is and not in the path specified

提问人:MyselfAndOnlyMe 提问时间:11/8/2021 最后编辑:marc_sMyselfAndOnlyMe 更新时间:11/8/2021 访问量:859

问:

我正在编写一个 PowerShell 脚本,我需要在C:\Users

我的脚本位于桌面上。

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

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

相反,它会创建目录:

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

如何直接在 ?C:\Users

PowerShell 目录 新建项

评论


答:

3赞 briantist 11/8/2021 #1

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

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

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

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

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

$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)
}

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