0

the paths are like this and none of these directory exist:

"D:\temp\test\abc.txt"  
"D:\temp2\test2\abc2.txt"
"D:\temp1\abc.txt"

I am trying to split the path and create directories only. I am trying below:

New-Item -Path "D:\temp\testing\abc.txt" -ItemType file  
Split-Path -Path "D:\temp\testing\abc.txt" -Resolve –IsAbsolute
script0207
  • 345
  • 1
  • 4
  • 12
  • What's your exact goal here? Create only the directory or also the files? Because if you want to create the file and all the directory tree at once, just add the `-Force` switch to your `New-Item` command. :) – Tuttu Jan 14 '19 at 13:16
  • goal is to create a directory only from the path – script0207 Jan 14 '19 at 13:18
  • https://stackoverflow.com/questions/16906170/create-directory-if-it-does-not-exist – Roland Molnar Jan 14 '19 at 13:22
  • Then you can do this : `New-Item -Path (Split-Path D:\temp\test\abc.txt) -ItemType Directory -Force`. Using `Split-Path` with no parameters will return you the parent container. Used with the `-Force` switch of `New-Item` will let you get the desired result. :) – Tuttu Jan 14 '19 at 13:33

1 Answers1

0

[edit - didn't see the comment by Tuttu. [*blush*] i will leave this here, but that one is the 1st answer.]

i think what you are looking for is the Split-Path cmdlet. [grin] something like this ...

$PathList = @(
    'c:\temp\test1\abc.txt'  
    'c:\temp\test2\subtest2-1\abc2.txt'
    'c:\temp\test3\subtest3-1\subtest3-1-1\abc.txt'
    )

foreach ($PL_Item in $PathList)
    {
    $NewDir = Split-Path -Path $PL_Item -Parent
    if (-not (Test-Path -LiteralPath $NewDir))
        {
        $Null = New-Item -Path $NewDir -ItemType Directory -Force
        }
    }

that made 3 new directories, two of them with sub-directories.

note that this does NOT take into account any input path that has no terminating file ... you will always get the parent path.

Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26