liveBook · Manning

New-Item

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

New-Item is a PowerShell cmdlet that creates a new item such as a file, directory, or other provider-managed resource.

New-Item creates a directory when an automation target does not exist. Pair it with Test-Path and a negated condition so setup continues instead of stopping. section 2.1.1

Use New-Item carefully inside reusable functions:

  • Specify -Path and -ItemType Directory when creating an archive folder. section 2.1.1
  • Pipe the command to Out-Null when its object should not become function output. section 2.1.1
  • Use Write-Verbose separately so callers can observe creation without receiving the cmdlet result. section 2.1.1

Create an archive directory

if(-not (Test-Path -Path $ZipPath)){ New-Item -Path $ZipPath -ItemType Directory | Out-Null; Write-Verbose "Created folder '$ZipPath'" } section 2.1.1

Listing 2.1 Set-ArchiveFilePath function
Function Set-ArchiveFilePath{                                   #1
    [CmdletBinding()]                                           #2
    [OutputType([string])]
    param(                                                      #3
    [Parameter(Mandatory = $true)]
    [string]$ZipPath,
 
    [Parameter(Mandatory = $true)]
    [string]$ZipPrefix,
 
    [Parameter(Mandatory = $true)]
    [datetime]$Date
    )
 
    if(-not (Test-Path -Path $ZipPath)){                        #4
        New-Item -Path $ZipPath -ItemType Directory | Out-Null
        Write-Verbose "Created folder '$ZipPath'"               #5
    }
    
    $timeString = $Date.ToString('yyyyMMdd')                    #6
    $ZipName = "$($ZipPrefix)$($timeString).zip"                #7
    $ZipFile = Join-Path $ZipPath $ZipName                      #8
 
    if(Test-Path -Path $ZipFile){                               #9
        throw "The file '$ZipFile' already exists"
    }
 
    $ZipFile                                                    #10
}

Inspect the complete Set-ArchiveFilePath function, including parameter validation, path construction, and New-Item integration. section 2.1.1

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Explains conditional creation, output suppression, and verbose reporting, but does not detail broader item types.
Examples
Uses Set-ArchiveFilePath to create an absent archive directory before constructing a dated ZIP path.
What you can do after
Apply it via PowerShell to create a missing directory while keeping function output predictable.
How it connects
Connects New-Item with Test-Path, Out-Null, Write-Verbose, Join-Path, and PowerShell functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.