diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 0866a8c399..a186349508 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -608,6 +608,7 @@ namespace Microsoft.PowerShell.Commands /// since it is optional for GetService and mandatory otherwise. /// [Parameter(Position = 0, ParameterSetName = "Default", ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] + [ValidateNotNullOrEmpty()] [Alias("ServiceName")] public string[] Name { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 new file mode 100644 index 0000000000..3762cdbe8a --- /dev/null +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 @@ -0,0 +1,43 @@ +Describe "Get-Service cmdlet tests" -Tags "CI" { + # Service cmdlet is currently working on windows only + # So skip the tests on non-Windows + BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + if ( -not $IsWindows ) { + $PSDefaultParameterValues["it:skip"] = $true + } + } + # Restore the defaults + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + } + + $testCases = + @{ data = $null; value = 'null' }, + @{ data = [String]::Empty; value = 'empty string' } + + Context 'Check null or empty value to the -Name parameter' { + It 'Should throw if is passed to -Name parameter' -TestCases $testCases { + param($data) + try { + $null = Get-Service -Name $data -ErrorAction Stop + throw 'Expected error on previous command' + } + catch { + $_.FullyQualifiedErrorId | Should Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' + } + } + } + Context 'Check null or empty value to the -Name parameter via pipeline' { + It 'Should throw if is passed through pipeline to -Name parameter' -TestCases $testCases { + param($data) + try { + $null = Get-Service -Name $data -ErrorAction Stop + throw 'Expected error on previous command' + } + catch { + $_.FullyQualifiedErrorId | Should Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' + } + } + } +}