diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 047cfa5692d..4aaf3881dc0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -761,14 +761,25 @@ private void ProcessCachedGroupOnWide(WideViewHeaderInfo wvhi, List static private int GetConsoleWindowWidth(int columnNumber) { + if (InternalTestHooks.SetConsoleWidthToZero) + { + return DefaultConsoleWidth; + } if (columnNumber == int.MaxValue) { if (_noConsole) { return DefaultConsoleWidth; } + try { + // if Console width is set to 0, the default width is returned so that the output string is not null. + // Fix added because console width on VSTS is equal to 0. + if (Console.WindowWidth == 0) + { + return DefaultConsoleWidth; + } return Console.WindowWidth; } catch diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 5b108a97978..3b5486182de 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1509,6 +1509,7 @@ public static class InternalTestHooks // Simulate 'System.Diagnostics.Stopwatch.IsHighResolution is false' to test Get-Uptime throw internal static bool StopwatchIsNotHighResolution; internal static bool DisableGACLoading; + internal static bool SetConsoleWidthToZero; /// This member is used for internal test purposes. public static void SetTestHook(string property, object value) 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 8be57d9fdda..fa8148a332e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -717,4 +717,19 @@ abc bcd $output = $obj | Format-Table | 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 -str | ForEach-Object {$_.length} | Sort-Object | Select-Object -Last 1 | Should -Be 120 + Format-Table -inputobject $testObject | Should -Not -BeNullOrEmpty + } + finally { + [system.management.automation.internal.internaltesthooks]::SetTestHook('SetConsoleWidthToZero', $false) + } + } }