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
