I am writing a PowerShell script and I need to create a directory in C:\Users
My script is located on the desktop.
My line of script to create the directory is this:
New-Item -ItemType "directory" -Force -Path "C:Users\username\scripts\documents"
It instead creates the directory:
C:\Users\username\Desktop\Users\username\scripts\documents
How can I make the new directory directly in C:\Users
?
CodePudding user response:
You are missing a backslash \
after the path root (the drive letter):
New-Item -ItemType "directory" -Force -Path "C:\Users\username\scripts\documents"
See also: https://docs.microsoft.com/en-us/dotnet/api/system.io.path.ispathrooted?view=net-5.0
A rooted path is file path that is fixed to a specific drive or UNC path; it contrasts with a path that is relative to the current drive or working directory. For example, on Windows systems, a rooted path begins with a backslash (for example,
\Documents
) or a drive letter and colon (for example,C:Documents
).Note that rooted paths can be either absolute (that is, fully qualified) or relative. An absolute rooted path is a fully qualified path from the root of a drive to a specific directory. A relative rooted path specifies a drive, but its fully qualified path is resolved against the current directory. The following example illustrates the difference.
$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)
}
(I did not include the [System.IO.Path]::IsPathFullyQualified()
call in the linked example, because it is not included in Windows PowerShell 5.1)