diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index d6431fd3ff6..b1a3cbac05d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -61,9 +61,18 @@ public class ConvertToJsonCommand : PSCmdlet /// be converted to their string equivalent. Otherwise, enum values /// will be converted to their numeric equivalent. /// - [Parameter()] + [Parameter] public SwitchParameter EnumsAsStrings { get; set; } + /// + /// Gets or sets the AsArray property. + /// If the AsArray property is set to be true, the result JSON string will + /// be returned with surrounding '[', ']' chars. Otherwise, + /// the array symbols will occur only if there is more than one input object. + /// + [Parameter] + public SwitchParameter AsArray { get; set; } + #endregion parameters #region overrides @@ -104,7 +113,7 @@ protected override void EndProcessing() { if (_inputObjects.Count > 0) { - object objectToProcess = (_inputObjects.Count > 1) ? (_inputObjects.ToArray() as object) : (_inputObjects[0]); + object objectToProcess = (_inputObjects.Count > 1 || AsArray) ? (_inputObjects.ToArray() as object) : (_inputObjects[0]); // Pre-process the object so that it serializes the same, except that properties whose // values cannot be evaluated are treated as having the value null. object preprocessedObject = null; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 index 8e9336a51f6..4fb734556f7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 @@ -35,4 +35,17 @@ Describe 'ConvertTo-Json' -tags "CI" { $ps.InvocationStateInfo.State | Should -BeExactly "Stopped" $ps.Dispose() } + + It "The result string is packed in an array symbols when AsArray parameter is used." { + $output = 1 | ConvertTo-Json -AsArray + $output | Should -BeLike "``[*1*]" + + $output = 1,2 | ConvertTo-Json -AsArray + $output | Should -BeLike "``[*1*2*]" + } + + It "The result string is not packed in the array symbols when there is only one input object and AsArray parameter is not used." { + $output = 1 | ConvertTo-Json + $output | Should -BeExactly '1' + } }