powershell - Generate month-folders and day-subfolders for a whole year -


i created script generates in given path (first parameter) folders each month (format yyyy_mm) , in each of folders subfolders each day (format yyyy_mm_dd).

the code works, there easier solution?

param( [string]$inppath = '', [string]$inpyear = '0' ) function dayfolder {   1..[datetime]::daysinmonth($inpyear,$month) | foreach-object {      $day = $_     new-item -itemtype directory -force -path ($inppath + '\' + $inpyear + '_' + ("{0:d2}" -f $month) + '\' + $inpyear + '_' + ("{0:d2}" -f $month) + '_' + ("{0:d2}" -f $day) ) } }  if ($inppath -eq '') {     echo 'no path in input! first parameter!' } else {     if ($inpyear -eq '0')     {       echo 'no year in input! second parameter! format: yyyy'     }     else     {     1..12 | foreach-object {              $month = $_             new-item -itemtype directory -force -path ($inppath + '\' + $inpyear + '_' + ("{0:d2}" -f $month))             dayfolder             }     }        } 

i think making things overly complicated providing defaults arguments , giving error messages when defaults used. if want parameters mandatory should declare them such. in fact can go further , declare them being valid path , number in particular range.

otherwise main observation new-item creates parent items needs, don't need create month folders separately.

there various ways build path string, think in case simplest format month , day , use single string (note _ valid character in variable name have use ${...} form of variable expansion in cases):

param(     # path existing folder.     [parameter(mandatory=$true)]     [validatescript({test-path $_ -pathtype 'container'})]      [string]$inppath,      # year must recent or in future. warranty expires 2100     [parameter(mandatory=$true)]     [validaterange(1999,2100)]     [int]$inpyear )  1..12 | foreach-object {     $month = "{0:d2}" -f $_     1..[datetime]::daysinmonth($inpyear,$month) | foreach-object {         $day = "{0:d2}" -f $_         new-item -itemtype directory -force -path "$inppath\${inpyear}_$month\${inpyear}_${month}_${day}"     } } 

the other thing if want use often, better turn function or cmdlet , can keep in module other cmdlets. if comment before each parameter becomes part of screen , can include description , examples screen in comment @ top of function declaration.

p.s. bloody powershell beginners recommend http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -