You can't do what you want with Write-Warning
.
Therefore, I will answer regarding your other concern.
Write-Host
is perfectly fine to use in a PowerShell 5+ script.
If you look at the articles recommending against its use, you will notice that the vast majority (if not all) were written before the introduction of PowerShell 5.
Nowadays, Write-Host
is a wrapper around Write-Information
.
The official documentation confirms this:
Starting in Windows PowerShell 5.0, Write-Host
is a wrapper for
Write-Information
This allows you to use Write-Host
to emit output to
the information stream. This enables the capture or suppression of
data written using Write-Host
while preserving backwards
compatibility.
The $InformationPreference
preference variable and -InformationAction
common parameter do not affect Write-Host
messages. The exception to
this rule is
-InformationAction Ignore
, which effectively suppresses
Write-Host
output.
Writing to the information stream using Write-Host
and / or Write-information
won't create problems with your output string.
Stream # Description Introduced in
1 Success Stream PowerShell 2.0
2 Error Stream PowerShell 2.0
3 Warning Stream PowerShell 3.0
4 Verbose Stream PowerShell 3.0
5 Debug Stream PowerShell 3.0
6 Information Stream PowerShell 5.0
* All Streams PowerShell 3.0
Bonus
You can also control the visibility of the information stream if you use an advanced function through the -InformationAction
parameter, provided you also bind the given parameter value to the Write-Host
statements in the function.
For instance, if you wanted to disable the Information stream by default unless requested otherwise:
function Get-Stuff {
[CmdletBinding()]
param ()
if (!$PSBoundParameters.ContainsKey('InformationAction')) {
$InformationPreference = 'Ignore'
}
Write-Host 'This is the stuff' -InformationAction $InformationPreference -ForegroundColor Green
}
# Hidden by default
Get-Stuff
# Force it to show
Get-Stuff -InformationAction Continue
Note
While technically it is not possible to use Write-Warning -NoNewLine
, you could look into manipulating the cursor position and resetting it to the end of the previous line, therefore doing the same.
However, I have limited experience with that and my observations regarding the subject were that you might end up having to create exceptions to comply with limitations of some console environments. In my opinion, this is a bit overkill...
Additional references
About_redirections