Creating new folders from command line tools has always been possible in Windows. We could use the command mkdir in the old command prompt. But how do you create a folder in PowerShell? You could use the command mkdir as well, but there is a better way.
In PowerShell, we can use the cmdlet New-Item to create a new directory. This cmdlet is more powerful than the old mkdir command.
In this article
In this article, I will show you how you can create a folder in PowerShell, with or without subdirectories, and more!
Let’s start with the basics, to create a new directory in PowerShell we are going to use the cmdlet New-Item. This cmdlet can be used to create files, folders, or symbolic links. In this article, we will focus on creating a folder.
To create a new directory we will need to specify the path where we want to create the folder and the name of the new folder:
New-Item -Path "c:\temp\" -Name "testfolder" -ItemType Directory
We can even shorten this by including the new folder name in the -path parameter and replacing -ItemType to -Type
# Create a new folder "testfolder-b" in the path c:\temp New-Item -Path "c:\temp\testfolder-b" -Type Directory # You can even leave out the path paremeter label New-Item "c:\temp\testfolder-b" -Type Directory
Personally, I prefer to use the -Name parameter in scripts, because it makes it easier for others to read your code and see which new folder is created where.
Create new Directory in current Location
To make a new directory in the current location of the PowerShell script (or the working location of your PowerShell session), we can simply leave out the -path parameter. Another, and more readable, option is to specify a . for the current path:
# Create a new directory in the current location New-Item -Name "testfolder-c" -Type Directory # Same result New-Item -Path '.\testfolder-c' -Type Directory
Creating Multiple Folders
It’s also possible to create multiple folders at once. To do this there are basically two methods that we can use. We can either loop through an array of folders to create or specify multiple folders in an array string.
If you only need to create a handful of folders, then the option below is the most convenient one to use:
New-Item -Path "c:\temp\folder1","c:\temp\folder2","c:\temp\folder3" -Type Directory
The other option is to use a ForEach-Object loop. This method can be used with a simple array, or can be used to create folders from a CSV file for example:
$folders = (
"folder4",
"folder5",
"folder6"
)
$folders | ForEach {New-Item -Path "c:\temp\" -Name $_ -Type Directory}
In the example below I have a simple CSV file with only the names of the folder. So we will need to add a header to be able to reference the folder names in the foreach loop. You can also pipe the ForEach loop directly behind the Import-CSV of course.
$folders = Import-CSV -Path C:\temp\example.csv -Header foldername
$folders | ForEach {New-Item -Path "c:\temp\" -Name $_.foldername -Type Directory}
Create Folders and Subfolders
One of the advantages of using PowerShell to create folders is that we can create folders and subfolders with a single command. This method is really handy when you need to create the same folder structure for new projects for example.
The New-Item cmdlet will create the parent folder automatically when it’s missing. So for example, if we want to create the directory budget inside the folder marketing, then we only need to specify the name “marketing\budget”. If the folder marketing doesn’t exist, then the New-Item cmdlet will create it automatically.
In the example above, I have specified the new folders in the -Name parameter. But that isn’t necessary. You can also specify the complete path in the -Path parameter or specify the parent path and only the subfolder in the -Name parameter. The commands below will all give the same result:
# All these commands will create the folder marketing and budget if they don't exist: New-Item -Path "c:\temp\" -Name "marketing\budget" -Type Directory New-Item -Path "c:\temp\marketing" -Name "budget" -Type Directory New-Item -Path "c:\temp\marketing\budget" -Type Directory
Using Wildcards to create Subfolders
Another powerful feature of the new-item cmdlet is the ability to use a wildcard in the path parameter. Now you might be wondering why you would need this when you create a folder with PowerShell. But this method can really be handy when you need to add a subfolder to multiple folders.
For example, you have a folder for each of your clients. You are asked to create a new subfolder for each client named contracts. Instead of getting each directory first with the Get-ChildItem cmdlet, you can simply use a wildcard:
New-Item -Path "c:\temp\*" -Name "contracts" -Type Directory
As you can see, the subfolder contracts is created in each folder in the path c:\temp:
Overwrite a Folder and using Test-Path
When a directory exists you can’t create it again, there is even no need for it. But when creating folders from a script you often want it to continue even if the directory exists. There are a couple of options for that, the preferred method is to use the Test-Path cmdlet. But we can also force the creation of the folder or simply mute the error (which is the least preferred option).
The -Force parameter does not really recreate the folder, it will only return the existing folder object without showing any errors:
New-Item -Path "c:\temp\" -Name "folder1" -Type Directory -Force
As mentioned it’s better to use the Test-Path cmdlet to check if a folder exists before you create it. This allows you to create a better error-handling solution in your scripts. To create the directory only when the folder doesn’t exist you can do the following:
$path = "C:\temp\folder1"
# Create the folder is the path doesn't exist
If (-not(test-path -Path $path)) {
New-Item -Path $path
}
Wrapping Up
The New-item cmdlet is a powerful cmdlet when it comes to creating files and folders in PowerShell. It replaces the mkdir command and allows you to easily create on or multiple folders including subfolders.
I hope you found this article helpful, if you have any questions, just drop a comment below.
To create a folder in PowerShell, you can use the `New-Item` command followed by the desired folder path.
New-Item -Path "C:\ExampleFolder" -ItemType Directory
Understanding PowerShell Commands
What is PowerShell?
PowerShell is a task automation framework that consists of a command-line shell and an associated scripting language. It is designed to help system administrators and power users automate the management of the Windows operating system and applications running on Windows. Unlike Command Prompt, which is limited in its functionality, PowerShell allows users to work with objects, making it a more powerful tool for managing and automating tasks.
Why Use PowerShell for File Management?
Using PowerShell for file management streamlines the process significantly. Here are some key benefits:
- Automation: PowerShell enables you to automate repetitive tasks, saving time and reducing human error.
- Batch Processing: You can manage multiple files and folders in a single command, enhancing efficiency.
- Scripting: Create scripts that can be run at any time to execute complex tasks with minimal input.
Get Folder PowerShell: A Quick Guide to Mastery
The Basics of Creating a Folder in PowerShell
Overview of the Command
To create a folder in PowerShell, the primary command to use is `New-Item`. This command allows you to create various types of items, including files and directories. The basic syntax for creating a folder is:
New-Item -Path "C:\Path\To\Your\Folder" -ItemType Directory
Example of Creating a Folder
Let’s walk through a simple example to create a folder in your Documents directory:
New-Item -Path "C:\Users\YourName\Documents\NewFolder" -ItemType Directory
In this command:
- Path specifies the location where the new folder will be placed.
- ItemType is set to Directory, indicating that we want to create a new folder.
Once the command is executed, a folder named NewFolder will be created in your Documents directory.
Delete File in PowerShell: A Simple Guide
Creating a New Directory with PowerShell
Utilizing `mkdir` Command
In addition to `New-Item`, PowerShell provides an alias, `mkdir`, which stands for make directory. This alias can be used interchangeably and often simplifies the command for folder creation. The syntax is straightforward:
mkdir "C:\Path\To\Your\NewFolder"
Advantages of using `mkdir`:
- It’s quicker to type and remember.
- It’s consistent with other command-line environments, making it easier for users transitioning from Unix-like systems.
Creating Nested Directories
PowerShell also allows you to create nested directories in a single command. This means you can create a parent folder and subfolders in one go. Here’s how you can do it:
New-Item -Path "C:\Path\To\Your\Folder\SubFolder1\SubFolder2" -ItemType Directory -Force
In this example:
- The -Force parameter ensures that any parent directories that do not yet exist will be created as well. This is helpful if you need to create a directory structure without worrying about whether the parent folders already exist.
Get Folder Size PowerShell: Quick Command Guide
PowerShell to Create a Folder with Dynamic Names
Using Date/Time in Folder Names
Creating folders with dynamic names can help in organizing backups or logs. You can leverage PowerShell’s capabilities to incorporate the current date and time in your folder names. Here’s an example:
$folderName = "Backup_" + (Get-Date -Format "yyyyMMddHHmmss")
New-Item -Path "C:\Backups\$folderName" -ItemType Directory
This command will create a folder named something like Backup_20230927153000 (depending on the current date and time). This flexibility is especially useful for automated tasks where you want unique folder names to avoid overwriting.
Tips for Naming Conventions
Best practices for naming folders include:
- Avoid special characters that may cause issues in file paths, such as `*`, `?`, or `|`.
- Use underscores (_) or hyphens (-) instead of spaces to enhance readability and compatibility in scripts and automation tools.
Mastering Credentials in PowerShell: A Quick Guide
Error Handling in PowerShell
Managing Errors during Folder Creation
Creating folders may sometimes lead to errors, such as invalid paths or permission issues. It’s crucial to implement error handling to manage these scenarios effectively. You can use a `Try-Catch` block like this:
Try {
New-Item -Path "C:\Path\To\Your\Folder" -ItemType Directory
} Catch {
Write-Host "Error: $_"
}
This structure allows the script to attempt to create the folder, and if an error occurs, it will catch that error and output a message indicating what went wrong.
Restart PowerShell: A Quick How-To Guide
Conclusion
Creating a folder in PowerShell is a straightforward task that can significantly enhance your file management capabilities. By mastering commands like `New-Item` and `mkdir`, you can efficiently create single or nested directories, utilize dynamic naming, and manage errors effectively. Whether you’re automating backups or organizing project files, leveraging PowerShell can save you time and effort.
As you continue to explore and practice these commands, you’ll find even more powerful ways to use PowerShell for file management. Stay tuned for more tips and tricks to boost your automation skills!
Mastering Write-Progress in PowerShell: A Quick Guide
Additional Resources
For further reading on PowerShell and its capabilities, consider exploring the official Microsoft documentation, online forums, and tutorials that cover advanced scripting and automation techniques. Mastering PowerShell can unlock a wealth of possibilities for your system management tasks.
Updated March 15, 2023
Introduction to PowerShell Create Directory
The command inline directory offers vast commands to create a folder or directory in PowerShell. The popular command used to create the directory is New-item. It can be created with different attributes also. Though they are not in-built commands in PowerShell, the mkdir and md commands are used to create directories. Using the New-item command in cmdlet, the folder is also created. The parameter itemtype is used to indicate the name and location of the folder where it wants to be created.
Key Takeaways
- The default directory in PowerShell is C: \ user\ name of the user.
- New-item is used to create files, folders, directories, registries, etc.
- The directory can be created using the mkdir, md command.
- Directories work on file system objects.
- .net framework class and System.io. a directory object is used to create directories.
- The path and related links are created along with the directory.
Overview of PowerShell Create Directory
File management is an important part; it is necessary to manage and segregate all the folders and give suitable access to the concerned resource. It should also perform other standard operations in backup folders and files in the Windows system. Though it may look difficult, it is possible with PowerShell to manage and work on the files easily. It reduces the quantity of manual work related to filing management.
When the user is creating a file or directory, ensure the filename. Then work on the script, which automatically checks if other files exist in the same name, and it goes to create a file if there is no other file with the same name.
How to Create a Directory in PowerShell?
The new directory can be created in multiple methods, few methods are given below; the new item is used to create new links, new folders, or files or directories. –itemtype should be specified along with the new command to create a directory and path name.
Code:
New- item – itemtype directory new folder
Output:
The absolute path is used in the new-item command where the new directory will be created in the new path. Using double quotes is more important to specify the folders and path. The new –item is also used to give the –path attribute, where the folder name and path should be given in a structured format.
Code:
New- item – itemtype – directory –path ‘C: \data \folder1
The new item is used to create an associative path and folders. In the above command, folder1 is created in the parent directory. Alternate, the directory’s path, and name can be separated by –name and –path values.
Create a Directory with the md and mkdir Command
The md command is used with the new-item command and works with all attributes and syntax. The md command is used to create a directory by giving the folder name. Md and mkdir represent the make directory.
How to Create Windows Using PowerShell?
Windows services usually run in the background without any user interaction. For example, here, the web server responds to an HTTP request for web pages within the network and works as a service and monitoring application that measures the log performance and hardware event data. These services can automatically be started when the system is booted. If they start as demand, it is requested by the application that depends on them. Service executed in the windows session is distinct from the user interface session. They can be executed in several system processes with special rights to constrain security risks.
Windows PowerShell can be created in PSSservice. Ps1 script by following the below steps.
By windows, PowerShell management service functions install and uninstall themselves. Then it stops and starts itself by management service functions in PowerShell.
Comprises the simple C# snippet, that designs the PSService.exec where the SCM expects by the Add-type command. Push the pssservice.exe file again to the psservice.ps1 script using the service operation. The service operation functions include onstop, onstart, response, and other events.
With the psservice.exe stub, the user can manage the SCM control panel and the available command-in-line tools. Be robust and push the command in any type of state. For example, it can be stopped automatically before uninstallation or stay dumb when triggered to initiate an already running service. Windows PowerShell version 2 features support windows 7 and all recent versions of windows.
New Command Creates a Directory
In simple terms, to develop a new file, give the new command in cmdlet. It is used to create all types of objects in PowerShell. The user has to mention the type of object which wants to be created in the cmdlet.
So, to create a folder or file in PowerShell. Give the new-item command. The below command will create the file1.txt. The itemtype denotes a file, creating a new file with the null content. Hence it creates a new empty text file for the user.
Code:
New – Item – path ‘ \\ shared \testfolder \file1.txt’ -itemtype file.
FAQ
Given below is the FAQ mentioned:
Q1. In Windows 11, How to open a new folder in PowerShell?
Answer:
Give PowerShell in the start option and select windows PowerShell application in the search bar. Go to C then windows, then system 32, then windows PowerShell, choose the v1.0 folder, and click on the PowerShell file.
Q2. How to open a directory in PowerShell?
Answer:
Using the new-item, mkdir, or md command. CD foobar is used to go to the directory where the user wants to go. CD is used to navigate to a set location. Set-location foobar can work as the same.
Q3. How to fix if the user is unable to go inside a directory?
Answer:
Check for permissions and give rwx rights. Sudo setfacl –m username –rwx name of the folder.
Conclusion
Hence there are multiple methods to create a directory using PowerShell. It can be executed according to user preference. Though PowerShell has a wide community, the queries will be responded to immediately.
Recommended Articles
This is a guide to PowerShell Create Directory. Here we discuss the introduction and how to create a directory in PowerShell. the new command creates a directory and FAQ. You may also have a look at the following articles to learn more –
- PowerShell Uptime
- Powershell Remotesigned
- PowerShell Start-Service
- PowerShell is not digitally signed
-
Using the
[System.IO]Namespace to Create Directory in PowerShell -
Using the File System Object to Create Directory in PowerShell
-
Using the
New-ItemCmdlet to Create Directory in PowerShell -
Using the
mdLegacy Command to Create Directory in PowerShell
In Windows PowerShell, there are multiple ways to create file directories or folders that we can fully integrate into our scripts.
This article will show how to create them using Windows PowerShell.
Using the [System.IO] Namespace to Create Directory in PowerShell
Using the Directory .NET Framework class from the system.io namespace is possible. To use the Directory class, use the CreateDirectory static method and supply a path to the new folder’s location.
This technique is shown here.
[System.IO.Directory]::CreateDirectory("C:\test\newfolder")
When the command above runs, it returns a DirectoryInfo class. However, we do not necessarily recommend this approach, but it is currently working and available.
Using the File System Object to Create Directory in PowerShell
Another way to create a directory is to use the Scripting.FileSystemObject object from Windows PowerShell.
This method is the same object that VBScript and other scripting languages used to work with the file system. It is swift and relatively easy to use.
After the object is created, Scripting.FileSystemObject exposes a CreateFolder method. The CreateFolder method accepts a string representing the path to create the folder.
After running, an object contains the path and other information about the newly-created directory.
$fso = New-Object -ComObject Scripting.FileSystemObject
$fso.CreateFolder('C:\test1')
Using the New-Item Cmdlet to Create Directory in PowerShell
The native Windows PowerShell commands are also available to create directories. One way is to use the New-Item cmdlet.
New-Item -Force -Path c:\test3 -ItemType Directory
When used, the -Force switch parameter will overwrite existing folders that have been already created. Instead, we can use the Test-Path cmdlet to check if the directory exists.
In the example below, we can create a script block to check if the directory exists. If the directory exists, it will not create the directory.
This syntax is one way of avoiding the -Force switch parameter.
$path = "C:\temp\NewFolder"
if (!(Test-Path $path)) {
New-Item -ItemType Directory -Path $path
}
Suppose we compare this command’s output with the output from the previous .NET command. The result is the same because the New-Item cmdlet and the [System.IO.Directory]::CreateDirectory command return a DirectoryInfo object.
It is also possible to shorten the New-Item command by leaving out the -Path parameter name and only supplying the full path as a data type string with the ItemType syntax. This revised command is shown here.
New-Item c:\test4 -ItemType directory
Some might complain that it was easier to create a directory in the old-fashioned command interpreter, cmd, because all they needed to type was md–-and typing md is undoubtedly easier than typing New-Item command.
Using the md Legacy Command to Create Directory in PowerShell
The previous example leads to the fourth way to create a directory (folder) using Windows PowerShell, using the md function.
The advantage of using the md command is that it is faster since it already knows you will create a directory. Therefore, you can leave the ItemType parameter and type the full path directly.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
| Введение | |
| Test-Path: проверить существование | |
| New-Item: Создать директорию | |
| Remove-Item: Удалить директорию | |
| Expand-Archive: распаковать архив | |
| Rename-Item: переименовать директорию | |
| Join-Path объединение путей | |
| Похожие статьи |
Проверить существование директории
Проверить есть ли в текущей директории поддиректория
swagger-ui
${SwaggerPath} = Join-Path ${pwd} «swagger-ui»;
If (Test-Path -path ${SwaggerPath}) {
Write-Host «swagger-ui dir exists» -f Green
} Else {
Write-Host «swagger-ui dir does not exist» -f Yellow
}
Проверить и если такой директории нет — скачать архив
$SWAGGER_URL = «https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.11.10.zip»;
${SwaggerPath} = Join-Path ${pwd} «swagger-ui»;
If (Test-Path -path ${SwaggerPath}) {
Write-Host «swagger-ui dir exists» -f Green
} Else {
Write-Host «swagger-ui dir does not exist — starting download» -f Yellow
Invoke-WebRequest $SWAGGER_URL -OutFile swagger-ui.zip
}
Создать директорию
Для создания новой директории используется команда
New-Item с ItemType directory
New-Item -Path «c:\» -Name «logfiles» -ItemType «directory»
Проверить наличие директории. Если её нет — создать.
If (Test-Path -path «test\mod\etc\») {
Write-Host «test\mod\etc\ dir exists» -f Green
} Else {
Write-Host «test\mod\etc\ dir does not exist — creating» -f Yellow
New-Item -Path «test\mod\» -Name «etc» -ItemType «directory»
}
Удалить директорию
Удалить директорию можно с помощью той же команды, которая удаляет файлы Remove-Item.
Нужно передать аргументы -LiteralPath, -Force и -Recurse.
Пример удаления директории dirname из её родительской директории.
Remove-Item -LiteralPath «dirname» -Force -Recurse
Распаковать архив
Распаковать архив в текущую директорию
Expand-Archive -Path swagger-ui.zip -DestinationPath .
Переименовать директорию
Rename-Item -Path swagger-ui-5.11.10 -NewName swagger-ui
Join-Path
Объединить пути можно следующим образом
$TMP_PATH = «C:/tmp_python»
$TMP_PYTHON_EXE = Join-Path -Path $TMP_PATH -ChildPath «python.exe»
Автор статьи: Андрей Олегович
Похожие статьи
| Windows | |
| PowerShell | |
| Alias | |
| Запросы к REST API | |
| Пользователи | |
| Сеть | |
| Установка | |
| Файлы | |
| Функции | |
| Циклы | |
| Ошибки PowerShell |
