New Item - PowerShell
Overview
The New-Item
command creates a new item in the specified location, such as a file, folder, registry key, or alias. It is commonly used for tasks like managing file systems, creating configuration items, and automating system management.
Syntax
New-Item [-Path] <String> [-Name] <String> [-ItemType] <String> [-Force] [[-Value] <Object>] [-Attributes <String>] [-Description <String>] [-Recurse] [-Confirm] [-WhatIf] [-PassThru]
Options/Flags
- -Path: Specifies the location where the new item should be created. Required.
- -Name: Sets the name of the new item. Required for files and folders.
- -ItemType: Indicates the type of item to create. Values can be “File”, “Directory”, “RegistryKey”, or “Alias”. Required unless creating an alias with -Value.
- -Force: Overwrites existing items without prompting for confirmation.
- -Value: Sets the initial value for the new item. Can be used to create registry values or aliases.
- -Attributes: Sets the file or directory attributes. Common values include “ReadOnly”, “Hidden”, and “Archive”.
- -Description: Specifies a description for the new item.
- -Recurse: Creates the new item and any necessary parent directories.
- -Confirm: Prompts for confirmation before performing the action.
- -WhatIf: Displays what would happen without actually performing the action.
- -PassThru: Returns the newly created item as an object.
Examples
Create a new file:
New-Item -Path "C:\Temp" -Name "TestFile.txt" -ItemType File
Create a new directory:
New-Item -Path "C:\My Documents" -Name "New Folder" -ItemType Directory
Create a new registry key:
New-Item -Path "HKLM:\Software\MyApplication" -Name "Settings" -ItemType RegistryKey
Create a new alias:
New-Item -Name "Get-MyFiles" -Value "Get-ChildItem -Path 'C:\Users\Me\Documents'" -ItemType Alias
Common Issues
- Error when path doesn’t exist: If the specified path doesn’t exist and
-Recurse
is not used, the command will fail. - Access denied: Ensure sufficient permissions to create items in the specified location.
- Invalid item type: Verify that the specified item type is supported by PowerShell.
Integration
New-Item
can be integrated with other commands to automate tasks. For example:
- Create a file and write content:
New-Item -Path "C:\Temp\TestFile.txt" -ItemType File | Add-Content "Hello World"
- Create a directory and copy files:
New-Item -Path "C:\My Documents\New Folder" -ItemType Directory; Copy-Item -Path "C:\Temp\*.txt" -Destination "C:\My Documents\New Folder"
Related Commands
- Remove-Item: Deletes the specified item.
- Move-Item: Moves the specified item to a new location.
- Set-ItemProperty: Modifies the properties of an existing item.