- Learn Four Ways to Use PowerShell to Create Folders
- Method 1
- Method 2
- Method 3
- Method 4
- Create folder in batch script and ignore if it exists
- 2 Answers 2
- Create directory if it does not exist
- 11 Answers 11
- Объект FileSystemObject методы CreateFolder и MoveFolder — Как создать новую папку и переместить ее
- Как создать новую папку
Learn Four Ways to Use PowerShell to Create Folders
February 21st, 2012
Summary: Microsoft Scripting Guy, Ed Wilson, shows four ways to create folders with Windows PowerShell, and he discusses the merits of each approach.
Hey, Scripting Guy! I am trying to find the best way to create a new folder while using Windows PowerShell. I have seen many ways of creating folders in scripts that I have run across on the Internet. They all seem to use something different. Is there a best way to create a new folder?
Hello GW,
Microsoft Scripting Guy, Ed Wilson, is here. This morning on Twitter, I saw a tweet that said “New-TimeSpan tells me that there are 41 days until the 2012 Scripting Games.” Indeed. Even though I have been busily working away on the Scripting Games, it seems awfully soon. I fired up Windows PowerShell and typed the following code:
New-TimeSpan -Start 2/21/12 -End 4/2/12
Sure enough, the returned TimeSpan object tells me that there are indeed 41 days until the 2012 Scripting Games. I decided I would like a cleaner output, so I used one of my Top Ten Favorite Windows PowerShell Tricks: group and dot. The revised code is shown here.
(New-TimeSpan -Start 2/21/12 -End 4/2/12).days
Both of these commands and the associated output are shown in the image that follows.
GW, you are correct, there are lots of ways to create directories, and I will show you four of them…
Method 1
It is possible to use the Directory .NET Framework class from the system.io namespace. To use the Directory class to create a new folder, use the CreateDirectory static method and supply a path that points to the location where the new folder is to reside. This technique is shown here.
When the command runs, it returns a DirectoryInfo class. The command and its associated output are shown in the image that follows.
I do not necessarily recommend this approach, but it is available. See the Why Use .NET Framework Classes from Within PowerShell Hey, Scripting Guy! blog for more information about when to use and not to use .NET Framework classes from within Windows PowerShell.
Method 2
Another way to create a folder is to use the Scripting.FileSystemObject object from within Windows PowerShell. This is the same object that VBScript and other scripting languages use to work with the file system. It is extremely fast, and relatively easy to use. After it is created, Scripting.FilesystemObject exposes a CreateFolder method. The CreateFolder method accepts a string that represents the path to create the folder. An object returns, which contains the path and other information about the newly created folder. An example of using this object is shown here.
$fso = new-object -ComObject scripting.filesystemobject
This command and its associated output are shown in the following image.
Method 3
GW, it is also possible to use native Windows PowerShell commands to create directories. There are actually two ways to do this in Windows PowerShell. The first way is to use the New-Item cmdlet. This technique is shown here.
New-Item -Path c:\test3 -ItemType directory
The command and the output from the command are shown here.
Compare the output from this command with the output from the previous .NET command. The output is identical because the New-Item cmdlet and the [system.io.directory]::CreateDirectory command return a DirectoryInfo object. It is possible to shorten the New-Item command a bit by leaving out the Path parameter name, and only supplying the path as a string with the ItemType. This revised command is shown here.
New-Item c:\test4 -ItemType directory
Some might complain that in the old-fashioned command interpreter, cmd, it was easier to create a directory because all they needed to type was md––and typing md is certainly easier than typing New-Item blah blah blah anyday.
Method 4
The previous complaint leads to the fourth way to create a directory (folder) by using Windows PowerShell. This is to use the md function. The thing that is a bit confusing, is that when you use Help on the md function, it returns Help from the New-Item cmdlet—and that is not entirely correct because md uses the New-Item cmdlet, but it is not an alias for the New-Item cmdlet. The advantage of using the md function is that it already knows you are going to create a directory; and therefore, you can leave off the ItemType parameter and the argument to that parameter. Here is an example of using the md function.
The command and its associated output are shown here.
You can see from the image above that the md function also returns a DirectoryInfo object. To me, the md function is absolutely the easiest way to create a new folder in Windows PowerShell. Is it the best way to create a new folder? Well, it all depends on your criteria for best. For a discussion of THAT topic, refer to my Reusing PowerShell Code—What is Best blog.
GW, that is all there is to creating folders. Join me tomorrow for more Windows PowerShell coolness.
Create folder in batch script and ignore if it exists
How do I create folder(and any subfolders) in batch script? What is important, if folder(or any subfolders) already exists, it should not return error.
For example, something like this:
- mkdir mydir — success(directory is now created)
- mkdir mydir\subdir — success(now mydir contains subdir )
- mkdir mydir — success(folder already exists, should not throw an error)
- mkdir mydir\subdir — success(folders already exists, should not throw an error)
What I actually need is just to ensure that folders structure exists.
2 Answers 2
A standard method to create a directory structure is:
By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.
The command MD creates the complete directory structure to specified directory with enabled command extensions.
MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.
But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.
The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.
But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don’t permit creation of the directory, etc.
So it is advisable to verify if the directory really exists which is done with:
It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist «%Directory%» would evaluate to false although there is no directory subdir 2 .
It is of course also possible to do the directory check first and create the directory if not already existing.
The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.
This batch code could be written more compact using operator || :
For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.
The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
Read also the Microsoft article about Using Command Redirection Operators.
Create directory if it does not exist
I am writing a PowerShell script to create several directories if they do not exist.
The filesystem looks similar to this
- Each project folder has multiple revisions.
- Each revision folder needs a Reports folder.
- Some of the «revisions» folders already contain a Reports folder; however, most do not.
I need to write a script that runs daily to create these folders for each directory.
I am able to write the script to create a folder, but creating several folders is problematic.
11 Answers 11
Try the -Force parameter:
See the New-Item MSDN help article for more details.
Test-Path checks to see if the path exists. When it does not, it will create a new directory.
The following code snippet helps you to create a complete path.
The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.
To call the function, use below statement:
The first line creates a variable named $path and assigns it the string value of «C:\temp\»
The second line is an If statement which relies on the Test-Path cmdlet to check if the variable $path does not exist. The not exists is qualified using the ! symbol.
Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.
md is the short version of typing out: New-Item -ItemType Directory -Path $path
Note: I have not tested using the -Force parameter with the below to see if there is undesirable behavior if the path already exists.
Объект FileSystemObject методы CreateFolder и MoveFolder — Как создать новую папку и переместить ее
Всем привет, с вами снова автор блога scriptcoding.ru. В этой публикации мы рассмотрим, как создать новую папку программным путём и вручную, а также, какие программные средства позволяют переместить заданный каталог.
И так, как создать новую папку? Если мы хотим создать новую папку в другом каталоге, на диске или рабочем столе, то можно просто нажать по пустой области правой кнопкой мыши и из контекстного меню выбрать пункт » Создать/Папку «. В итоге, в указанном месте появится новый каталог с именем Новая папка. Если мы работает с редактором Total Commander , то тут, что бы создать новую папку достаточно нажать клавишу F7, ввести название и вёе, работа сделана.
Как создать новую папку
Теперь давайте перейдем к программированию, точнее к объекту FileSystemObject и двум его методам:
CreateFolder (foldername) – Метод показывает, как создать новую папку, в качестве параметра мы указываем имя или полный путь к новому каталогу. Если просто указать имя каталога, то он создастся в текущей папке (откуда был запущен сценарий). Важно, если произойдет попытка создать новую папку с именем, с каким уже есть директория, то произойдёт ошибка.
MoveFolder (source, destination) – Собственно, метод отвечает за перемещение одного или группы каталогов. Видим, что ему передаются два параметра:
- source – путь к папке, которую нужно переместить, можно использовать подстановочные знаки «?» – любой один символ или «*» – любое количество символов. В случае использования подстановочных знаков, мы можем переместить сразу несколько каталогов.
- destination – путь к каталогу, в который должно производиться перемещение.
Хорошо, с теорией разобрались, теперь можно приступить к программированию. Напишем два сценария, один на языке vbscript, а другой на языке jscript. Их задача – показать, как создать новую папку, потом создать еще девять директорий и используя подстановочные знаки переместить их в ранее созданную директорию.
Давайте рассмотрим логику программного кода:
Сначала мы подключаем объект WScript.Shell, который нам нужен для получения пути к текущей директории. Путь будет храниться в переменной cur_dir, для получения пути мы используем свойство CurrentDirectory.
Далее происходит подключение объекта FileSystemObject, он позволит нам использовать метод CreateFolder, что бы показать, как можно создать новую папку с именем «Новый каталог_vbs» в текущей директории.
Далее мы используем цикл for (более детально я описал логику его работы в статье Урок_6_Циклы vbscript). Цикл содержит 9 итераций, то есть, будет создано 9 каталогов в текущей папке.
Ну и наконец, мы используем подстановочные знаки в методе MoveFolder для перемещения 9 папок в одну заданную.
Хорошо, а вот аналогичный пример на языке jscript:
Тут в принципе всё тоже, только стоит обратить внимание, что вместо одной косой черточки мы прописали две.
И так, в этой статье мы рассмотрели методы CreateFolder и MoveFolder объекта FileSystemObject, которые показывают, как создать новую папку и как её переместить.
Спасибо за внимание. Автор блога Владимир Баталий