|
2 | 2 | external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml |
3 | 3 | Locale: en-US |
4 | 4 | Module Name: Microsoft.PowerShell.Utility |
5 | | -ms.date: 09/26/2023 |
| 5 | +ms.date: 04/01/2026 |
6 | 6 | online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-host?view=powershell-5.1&WT.mc_id=ps-gethelp |
7 | 7 | schema: 2.0.0 |
8 | 8 | title: Write-Host |
@@ -35,7 +35,7 @@ a string to use to separate displayed objects. The particular result depends on |
35 | 35 | hosting PowerShell. |
36 | 36 |
|
37 | 37 | > [!NOTE] |
38 | | -> Starting in Windows PowerShell 5.0, `Write-Host` is a wrapper for `Write-Information` This allows |
| 38 | +> Starting in Windows PowerShell 5.0, `Write-Host` is a wrapper for `Write-Information`. This allows |
39 | 39 | > you to use `Write-Host` to emit output to the information stream. This enables the **capture** or |
40 | 40 | > **suppression** of data written using `Write-Host` while preserving backwards compatibility. |
41 | 41 | > |
@@ -261,8 +261,28 @@ cmdlet sends to it. |
261 | 261 | separated by a single space. This can be overridden with the **Separator** parameter. |
262 | 262 |
|
263 | 263 | - Non-primitive data types such as objects with properties can cause unexpected results and not |
264 | | - provide meaningful output. For example, `Write-Host @{a = 1; b = 2}` will print |
265 | | - `System.Collections.DictionaryEntry System.Collections.DictionaryEntry` to the host. |
| 264 | + provide meaningful output. For example, `@{a = 1; b = 2} | Write-Host` will print |
| 265 | + `System.Collections.Hashtable` to the host. |
| 266 | + |
| 267 | + To work around this issue, you can manually create the string format you need with either string |
| 268 | + interpolation or the format operator (`-f`). You can also pass the object to the |
| 269 | + [Out-String](Out-String.md) command before passing it to `Write-Host`. The following snippet |
| 270 | + shows examples of each approach: |
| 271 | + |
| 272 | + ```powershell |
| 273 | + $ht = @{a = 1; b = 2} |
| 274 | + # String interpolation |
| 275 | + $ht.Keys.ForEach({ "[$_, $($ht[$_])]" }) -join ' ' | Write-Host |
| 276 | + # Format operator |
| 277 | + "[{0}, {1}] [{2}, {3}]" -f @('a', $ht.a, 'b', $ht.b) | Write-Host |
| 278 | + # Out-String |
| 279 | + $ht | Out-String | Write-Host -NoNewline |
| 280 | + ``` |
| 281 | + |
| 282 | + For more information about string interpolation, see the article |
| 283 | + [Everything you wanted to know about variable substitution in strings](/powershell/scripting/learn/deep-dives/everything-about-string-substitutions). |
| 284 | + For more information about the format operator, see |
| 285 | + [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md#format-operator--f). |
266 | 286 |
|
267 | 287 | ## RELATED LINKS |
268 | 288 |
|
|
0 commit comments