In order to convey information to the user, you already know that Write-Host should not be used at all. There are exceptions to that rule, of course—mainly when querying the user for information, or when displaying one-time information, such as a consent to the usage of telemetry.
Other than that, make use of the following streams, as required by the type of message that you need to convey:
Write-Verbose | Verbose information that explains what the cmdlet is doing at the moment |
Write-Debug | Debug information that should help you debug the code if a user has issues with it |
Write-Information | Taggable messages that can be attributed to, like components in your script |
Write-Warning | Warnings that are visible, by default |
Write-Error | ErrorRecords that are visible, by default |
This way, the user has full control over the messages that they see, by setting the different Action parameters, such as ErrorAction, or by enabling the Verbose and Debug switches or preferences:
function Remove-ContosoVm
{
[CmdletBinding()]
param
(
# A comma-separated list of VM names to deprovision
[Parameter(
Mandatory,
HelpMessage = 'Please enter a comma-separated list of VM names'
)]
[string[]]
$ComputerName,
# An optional timeout in minutes for this operation
[Parameter()]
[int]
$TimeoutInMinutes = 5
)
Write-Verbose -Message "Deprovisioning $ComputerName"
Write-Verbose -Message "Shutting down $ComputerName"
foreach ($machine in $ComputerName)
{
Write-Debug -Message 'Calling Hyper-V cmdlets to shut down machine'
if ($true)
{
Write-Error -Message 'Could not shut down VM prior to removing it.' -TargetObject $machine
}
}
}
Remove-ContosoVm -ComputerName node1
Remove-ContosoVm -ComputerName node1,node2 -Verbose
Remove-ContosoVm -ComputerName node1,node2 -Verbose -ErrorAction SilentlyContinue