2

I'm trying to create directories at some target location, if they don't exist.

The name of the directory is from another source-location.

for each directory name in C:\some\location
create a new directory of the same name in C:\another\location.

for example.

c:\some\location\
                \apples
                \oranges

to
c:\another\location\
                   \apples
                   \oranges

so in effect i'm recreating all the folders from source -> to -> target. NOT recursive, btw. just top level.

So i've got this so far with PS:

dir -Directory | New-Item -ItemType Directory -Path (Join-Path "C:\jussy-test\" Select-Object Name)

or

dir -Directory | New-Item -ItemType Directory -Path "C:\new-target-location\" + Select-Object Name

and i'm stuck. I'm trying to get that last bit right. but anways, maybe someone has a nicer idea in their head?

1
  • one-liner: dir -Path C:\some\location\* -Directory | % { New-Item -ItemType Directory -Path C:\another\location\ -Name $_.Name } Commented May 24, 2016 at 2:51

1 Answer 1

2

You're very close with your first attempt. The main thing you're missing is how to iterate over the output of Get-Childitem (aka dir). For that, you need to pipe to Foreach-Object

$srcDir = 'c:\some\location'
$destDir = 'c:\another\location'

dir $srcDir -Directory | foreach {
  mkdir (join-path $destDir $_.name) -WhatIf
}

Inside the foreach, the variable $_ holds the current object, and $_.Name selects the Name property. (This also uses mkdir as a substitute for New-Item -Directory, but they're mostly interchangeable).

Once you know what this code is doing, remove the -WhatIf to have it actually create the directories.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.