The OutputType attribute declares the .NET type of the value a PowerShell function is expected to return. For an archive-path function that returns a file name, use [OutputType([string])]. section 2.1.1
Use the attribute as part of a maintainable function or script structure:
- Place [OutputType()] after [CmdletBinding()] at the beginning of a function. section 2.1.1
- Declare a specific type when the function has a known output, such as [string] for an archive file path. section 2.1.1
- Include OutputType attributes alongside comment-based help, CmdletBinding, and a parameter block in reusable scripts. section 2.1.7
Declaring an archive-path result
Function Set-ArchiveFilePath { [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory = $true)] [string]$ZipPath, [Parameter(Mandatory = $true)] [string]$ZipPrefix, [datetime]$Date = (Get-Date) ) # Builds and returns the archive file path. } $ZipFile = Set-ArchiveFilePath @ZipParameters # L:\Archives\LogArchive-20210110.zip section 2.1.1 section 2.1.7
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 implementation, including its declared string output and path-handling logic. section 2.1.1
