2016-05-24 26 views
2

ディレクトリが存在しない場合は、いくつかのターゲット場所にディレクトリを作成しようとしています。Powershellでディレクトリを作成しようとしています

ディレクトリの名前は別のソース場所からのものです。 C:\some\location
内の各ディレクトリ名の

は、例えばC:\another\location.

に同じ名前の新しいディレクトリを作成します。

c:\some\location\ 
       \apples 
       \oranges 

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

source -> to -> targetからすべてのフォルダを再作成しています。 再帰的ではありません。ちょうどトップレベル。

だから私はPSで、これまでこれを持っている:

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

または

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

と私はこだわっています。私はその最後のビットを得ようとしています。とにかく、誰かが彼らの頭の中でより良いアイデアを持っているのだろうか?

+0

ワンライナー: 'dir -Path C:\ some \ location \ * -Directory | %{New-Item -ItemTypeディレクトリ - パスC:\ another \ location \ -Name $ _。Name} ' – xXhRQ8sD2L7Z

答えて

2

あなたの最初の試みに非常に近いです。欠けている主なものは、Get-Childitem(別名dir)の出力をどのように反復するかです。そのためには、変数$_現在のオブジェクトを保持し、$_.Nameは、Nameプロパティを選択し、foreach内部Foreach-Object

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

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

に配管する必要があります。 (New-Item -Directoryの代わりにmkdirも使用されていますが、ほとんどの場合互換性があります)。

このコードが何を行っているか分かったら、実際にディレクトリを作成するには-WhatIfを削除してください。

関連する問題