diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 0f21310107..cd0c8fc4f6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -761,6 +761,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// static private int GetConsoleWindowWidth(int columnNumber) { + if (InternalTestHooks.SetConsoleWidthToZero) + { + return DefaultConsoleWidth; + } + if (columnNumber == int.MaxValue) { if (_noConsole) @@ -769,7 +774,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } try { - return Console.WindowWidth; + // if Console width is set to 0, the default width is returned so that the output string is not null. + // This can happen in environments where TERM is not set. + return (Console.WindowWidth != 0) ? Console.WindowWidth : DefaultConsoleWidth; } catch { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index d37a66631b..f6c2684e43 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1387,6 +1387,7 @@ namespace System.Management.Automation.Internal // Simulate 'System.Diagnostics.Stopwatch.IsHighResolution is false' to test Get-Uptime throw internal static bool StopwatchIsNotHighResolution; internal static bool DisableGACLoading; + internal static bool SetConsoleWidthToZero; // A location to test PSEdition compatibility functionality for Windows PowerShell modules with // since we can't manipulate the System32 directory in a test diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 1ddf8694a0..5cd6ef9039 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -800,4 +800,18 @@ A Name B $output = $obj | Format-Table -Wrap | Out-String $output.Replace("`r","").Replace(" ",".").Replace("`n","^") | Should -BeExactly $expectedTable.Replace("`r","").Replace(" ",".").Replace("`n","^") } + + It "Should not return null when the Console width is equal to 0" { + [system.management.automation.internal.internaltesthooks]::SetTestHook('SetConsoleWidthToZero', $true) + try + { + # Fill the console window with the string, so that it reaches its max width. + # Check if the max width is equal to default value (120), to test test hook set. + $testObject = @{ test = '1' * 200} + Format-table -inputobject $testObject | Out-String -Stream | ForEach-Object{$_.length} | Sort-Object -Bottom 1 | Should -Be 120 + } + finally { + [system.management.automation.internal.internaltesthooks]::SetTestHook('SetConsoleWidthToZero', $false) + } + } }