Несколько каталогов: эквивалент PowerShell для "mkdir dir "?

2448
Mr. Kennedy

Каков синтаксис для создания нескольких каталогов с PowerShells md (или mkdir, New-Item ...), эквивалентных команде 'nix, mkdir chт.е.

~/parent_dir/  ch1/  ch2/  ch3/  ch4/  ch5/  ch6/  ch7/  ch8/  ch9/  

Я посмотрел на страницах руководства и получил помощь для примеров, но я не знаю синтаксис для PowerShell, чтобы сделать такую ​​простую вещь. Спасибо.

11

3 ответа на вопрос

22
Bob

Вам не нужно вызывать mkdir несколько раз, потому что вы New-Itemможете использовать массив путей. Например:

mkdir $(1..9 | %{"ch$_"}) 

@DavidPostill объяснил большинство понятий в своем ответе . Это также использует преимущества интерполяции строк вместо выполнения явной конкатенации. Кроме того, %вместо этого используется сокращение ForEach-Object, но оно имеет то же значение.

К сожалению, не представляется простым способом интерполировать строку в массив строк, как в bash.

Oh. A much simpler solution. Should I delete my beginners effort? DavidPostill 7 лет назад 0
@DavidPostill You've explained in far more detail than I. This might be more of an addendum to your answer :P Bob 7 лет назад 2
@DavidPostill please don't delete it - your explanation is very useful Mr. Kennedy 7 лет назад 2
Bob, excellent point about only invoking mkdir once with this syntax. Mr. Kennedy 7 лет назад 0
Maximally golfed version: `md(0..9|%{"ch$_"})` Ben N 7 лет назад 3
@BenN s/golf/obfuscat/ :) I need a translator for that. Is there something that translates back and forth? DavidPostill 7 лет назад 0
@DavidPostill `md` is a standard alias for `mkdir`, which is a PowerShell function. `%`, as Bob mentioned, is a standard alias for `ForEach-Object`. Double-quoted strings interpolate variables, so `"ch$_"` is equivalent to `'ch' + $_`. You can look up an alias by running `Get-Command` (`gcm`) on it. Ben N 7 лет назад 2
Bob and @BenN , with this syntax, how to move corresponding ch#.files into ch#/ directories? This (and similar incantations) are failing: `mv $( 1..9 | %{ "ch$_*.*" } { "ch$_" } )` Mr. Kennedy 7 лет назад 0
Ahh... got it: `mv $( 1..9 | %{ "ch$_*.* ch$_" } )` Mr. Kennedy 7 лет назад 0
Good point! Any idea how to pipe git add and commit commands to these folders so each corresponding set has their update comments with corresponding #s? Mr. Kennedy 7 лет назад 0
@Mr.Kennedy ...are you sure that works? I don't think move can take multiple destinations at a time, so you'll have to go with a pipeline as in David's answer for a move. Do keep in mind that "ch1*.*" will catch "ch11.txt" as well... Bob 7 лет назад 0
Bob, whoops - you are correct, sir! My bad! Mr. Kennedy 7 лет назад 0
@Mr.Kennedy Something like: `1..9 | %{"ch$_"} | %` or `1..9 | %{$name = "ch$_"; git add "$name"; git commit -m "$name"}`. These comments are getting a bit long now, so if you have further questions - please ask them as questions, or maybe drop into chat. Bob 7 лет назад 1
16
DavidPostill

Какой синтаксис для создания нескольких каталогов с PowerShell

Используйте следующую команду:

0..9 | foreach $_{ New-Item -ItemType directory -Name $("ch" + $_) } 

Как это устроено:

Пример:

> 0..9 | foreach $_{ New-Item -ItemType directory -Name $("ch" + $_) }   Directory: F:\test   Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 25/09/2016 14:57 ch0 d----- 25/09/2016 14:57 ch1 d----- 25/09/2016 14:57 ch2 d----- 25/09/2016 14:57 ch3 d----- 25/09/2016 14:57 ch4 d----- 25/09/2016 14:57 ch5 d----- 25/09/2016 14:57 ch6 d----- 25/09/2016 14:57 ch7 d----- 25/09/2016 14:57 ch8 d----- 25/09/2016 14:57 ch9 
There is nothing less verbose than entering the following: `1..9 | % $_{ md -name $("ch" + $_) }` ? Mr. Kennedy 7 лет назад 3
I think so. But I'm no PowerShell expert. DavidPostill 7 лет назад 1
Ha - me neither! ...as a follow up to this, if the parent dir were full of files prepended with corresponding ch#s, would `1..9 | % $_{ mv ch$_.* ch$_ }` put all the ch#.ext files in the corresponding ch#/ directories? Mr. Kennedy 7 лет назад 0
It looks OK, but I suggest you try it and see :) DavidPostill 7 лет назад 1
Oh, of course, I've been trying various incatations to no avail :\ Mr. Kennedy 7 лет назад 0
a-HA - got it: `1..9 | % $_{ mv ch$_*.* ch$_ }` :^D Mr. Kennedy 7 лет назад 1
YaY - `git add` worked: `1..9 | % $_{ git add $("ch" + $_) }` ...but this: `1..9 | % $_{ git commit -m $("ch" + $_) }` will take some thinking upon... Thanks again, IRL, you have a cup of coffee on me anytime! Mr. Kennedy 7 лет назад 0
I've added some more explanation to the answer (how it works). DavidPostill 7 лет назад 0
Very useful explanation. In the continuing case of taking these new directories and moved files to a github repository, would this long piping add and commit files so each ch# dir and files have a corresponding ch# update comment? `1..9 | % $_{ git add $("ch" + $_) } | % $_{ git commit -m $("ch" + $_) }` Mr. Kennedy 7 лет назад 0
I don't know. I'm still a PowerShell beginner. I had to look things up to answer your question ;) DavidPostill 7 лет назад 0
K - if i find out how, I'll post a solution, thx!!! Mr. Kennedy 7 лет назад 0
@Mr.Kennedy Couple things. You should try running the `git add` and see what it returns - keep in mind that `$_` inside a foreach is only each individual array entry of the last pipeline item (which means the `commit` step in your example won't get raw numbers, so adding `ch` again is probably wrong). Also, in your example, the commits would only(?) run after all adds are done, which means the first commit would get everything... Alternatively, you could use multiple statements (separated by `;`) inside a single foreach step. Bob 7 лет назад 1
Thanks - your insights are very helpful and yes - everything got "ch1" as an update comment. Mr. Kennedy 7 лет назад 0
Я внесу несколько более краткую альтернативу: 1..9 | mkdir -Name {"ch $ _"} OldFart 7 лет назад 0
1
mamun

Я бы использовал для петлевой версии, так как она легко запоминается и может применяться во многих ситуациях. Даже это может быть использовано для нескольких команд.

Для эквивалента этой команды bash:

для меня в ; сделать
MKDIR CH $ я
сделал

... в использовании PowerShell:

for($i=1; $i -le 10; $i++)  
Мамум, не могли бы вы уточнить - я получаю сообщение об ошибке при запуске вашего кода из командной строки PowerShell или в виде сценария ps1: «Отсутствует открытие» («после ключевого слова» для »). Эта команда:« foreach ($ i in »). 1..9) `получает мне пронумерованные каталоги apter ch, но я не понимаю ваш цикл for ...; do ... done. Mr. Kennedy 7 лет назад 0
Цикл for, который я здесь использовал, предназначен для оболочки bash (/ bin / sh). Я всегда меняю свою оболочку на bash, так как я привык к этой оболочке. Для PS вы должны использовать другой синтаксис для цикла for (см. Прикрепленную ссылку http://ss64.com/ps/for.html). mamun 7 лет назад 0
PowerShell: `for ($ i = 1; $ i -le 10; $ i ++) ` спасибо, мамон, но я еще не "Борн снова ...";) (и при этом я не знаю C ++ , но мне кажется, что я понимаю, что значат "$ i-le" (если меньше или равно?) и "$ i ++" (~ "i + = 1"?) и делают в команде ... Mr. Kennedy 7 лет назад 1
Да, аргумент может быть прочитан как для (инициализировать i от 1; до тех пор, пока i меньше или равен 1; увеличить i на 1) mamun 7 лет назад 1

Похожие вопросы