Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create folders with leading zeroes in Powershell

Tags:

powershell

I've been using this script to create folders:

$i = 1
cd\
md d:\user$1
$i++

However it spits out folder like these...

d:\user1
d:\user2
d:\user3

What i want is two leading zeros, so that when i get to 009 it gracefully switches to a single leading zero.
Like wise at 099 it should transition to 100.

This is what I want it to output:

d:\user001
d:\user010
d:\user100

Currently i'm inserting the zeros into the script to before the $i, and removing it as it jumps into the second and third digits.
Everything i have read mentions using a string to get the preceding zeros.

Is that the only way?

Question from:
Reddit: Get powershell to count and include the leading zeros without using a string?

like image 244
Vasili Syrakis Avatar asked Mar 20 '14 11:03

Vasili Syrakis


People also ask

How do I create multiple folders in PowerShell?

2. How to create multiple folders at once using PowerShell. PowerShell offers a similar method to create multiple folders at the same time in Windows. Start PowerShell (look for powershell using the search field on your taskbar) and use the cd command to get to the folder where you want to create the new folders.

How do I create a folder in PowerShell?

To create a folder in PowerShell, use the New-Item cmdlet indicating the location and name of the folder and set the itemType parameter with the value Directory to indicate that you want to create a folder.

How do I create a remote computer folder using PowerShell?

Simply call createNewRemoteFolder "<Destination-Path>" to create the new folder. Save this answer.


2 Answers

use something like this:

0..10 | % { "user{0:000}" -f $_ } | % { New-Item -ItemType directory -Name $_ }
like image 136
CB. Avatar answered Oct 03 '22 14:10

CB.


Just replace your md command with something like:

md ( "d:\user" + ( "{0:D3}" -f $i ))

Still kinda arcane, but seems to work for me...

like image 44
Hunter Eidson Avatar answered Oct 03 '22 13:10

Hunter Eidson