Repository navigation
Adding Comment, Reason and Shutdown/RestartDelay parameters for Stop/Restart-Computer cmdlet - #27721
PRASOON KARUNAN V (kvprasoon) wants to merge 43 commits into
Conversation
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
There was a problem hiding this comment.
Pull request overview
This PR extends the Stop-Computer and Restart-Computer cmdlets with additional shutdown-tracker-related parameters (comment, reason, delay) to align more closely with shutdown.exe scenarios from #4857, and updates the WSMan/CIM invocation to call Win32ShutdownTracker so that metadata can be passed to the OS.
Changes:
- Add a
ShutdownReasonsenum and expose new cmdlet parameters (Comment,Reason, and delay-related parameters). - Switch WSMan shutdown/restart invocation to
Win32ShutdownTrackerand passTimeout,Comment,ReasonCode, andFlags. - Add Pester coverage for the new
-Commentand-Reasonparameters.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs |
Introduces shutdown reason enum/parameters and switches WSMan shutdown invocation to Win32ShutdownTracker with additional CIM parameters. |
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1 |
Adds tests asserting Stop-Computer accepts -Comment and -Reason. |
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 |
Adds tests asserting Restart-Computer accepts -Comment and -Reason. |
Comments suppressed due to low confidence (4)
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1482
[ValidateRange(0, ValidateRangeKind.Positive)]is not a validValidateRangeAttributeoverload and is likely to break compilation. Use a numeric range (as done forRestartDelay) to allow 0..UInt32.MaxValue.
[Parameter]
[ValidateRange(0, ValidateRangeKind.Positive)]
public UInt32 ShutdownDelay { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1489
StopComputerCommand.Commentis passed through to the Win32ShutdownTracker call even when the parameter isn't bound. Defaulting it tostring.Emptyavoids sendingnullto CIM/WMI and also matches theRestart-Computerimplementation.
[Parameter]
[ValidateNotNullOrEmpty]
public string Comment { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1536
-Reason Plannedcannot work forStop-Computerbecause the switch doesn't handle thePlannedenum name; it falls through todefaultand sendsOtherinstead.
case "Application":
flags[2] = ShutdownReasons.Application;
break;
case "Hardware":
flags[2] = ShutdownReasons.Hardware;
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:2548
flags[2]is populated withShutdownReasonsenum values, but the CIM parameter is declared asUInt32. Passing a boxed enum here can cause runtime type validation failures inCimMethodParameter.Create. Convert the value touintbefore adding the parameter.
methodParameters.Add(CimMethodParameter.Create(
"ReasonCode",
flags[2],
Microsoft.Management.Infrastructure.CimType.UInt32,
CimFlags.None));
…o feat/stopmessage-4857
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
Suppressed comments (7)
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1:51
- Stop-Computer -Reason is only available in the non-UNIX implementation, so this test needs to be skipped on Unix to avoid NamedParameterNotFound failures.
It "Should support Reason types" {
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1:50
- Restart-Computer -Reason is only available in the non-UNIX implementation, so this test needs to be skipped on Unix to avoid NamedParameterNotFound failures.
It "Should support Reason types" {
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1482
- Stop-Computer’s Comment property defaults to null when not bound, but ProcessRecord always forwards it to the CIM "Comment" parameter with CimFlags.None. This can fail at runtime if null isn’t accepted by the CIM layer/method. Consider defaulting to an empty string (and avoid rejecting empty strings for an optional comment).
/// Provide a comment for shutting down the computer.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Comment { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1526
- Stop-Computer has a public ShutdownReasons enum that includes Planned, but the Reason switch does not handle "Planned". Supplying -Reason Planned will currently fall through to default and be treated as Other.
switch (Reason.ToString())
{
case "Application":
flags[2] = ShutdownReasons.Application;
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:359
- RestartDelay (and similarly ShutdownDelay) doesn’t specify units in the parameter name. In this codebase, time-based parameters generally include units (e.g., TimeoutSec, Delay). Consider renaming to RestartDelaySec/ShutdownDelaySec (optionally keep an alias for back-compat).
/// Specify a delay before the reboot occurs.
/// </summary>
[Parameter(ParameterSetName = DefaultParameterSet)]
[ValidateRange(0, UInt32.MaxValue)]
public UInt32 RestartDelay { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:359
- RestartDelay is a new user-facing parameter but there are no Pester tests exercising it (unlike Comment/Reason). Adding a test would help prevent regressions in parameter binding and the WSMan invocation path.
[Parameter(ParameterSetName = DefaultParameterSet)]
[ValidateRange(0, UInt32.MaxValue)]
public UInt32 RestartDelay { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1475
- ShutdownDelay is newly introduced but there are no Pester tests covering it. A basic test that Stop-Computer accepts -ShutdownDelay and returns successfully under the testhook would help.
[Parameter]
[ValidateRange(0, ValidateRangeKind.Positive)]
public UInt32 ShutdownDelay { get; set; }
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
Suppressed comments (7)
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1528
- The
switch (Reason.ToString())block is redundant:Reasonis already a strongly-typed enum with the same values being assigned in each case. Keeping this large string-based mapping increases maintenance risk and makes it easier for the enum values and mapping to drift. Consider replacing the whole switch with a single assignment (for example,flags[2] = (uint)Reason;).
object[] flags = new object[] { 0, 0, 0, 1 };
flags[0] = ShutdownDelay;
flags[1] = Comment;
flags[2] = Reasons.Planned;
switch (Reason.ToString())
{
case "Application":
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1:50
- This test isn't skipped on non-Windows, but the
-Reasonparameter is only available in the Windows implementation ofRestart-Computer(the cmdlet is compiled out under#if !UNIX). This will fail on Unix withNamedParameterNotFound.
It "Should support Reason types" {
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:2547
ReasonCodeis declared asCimType.UInt32, butflags[2]is populated with theReasonsenum value. Passing the enum object relies on implicit conversion inside MI; cast/convert touintexplicitly to ensure the value type matches the declared CIM type.
methodParameters.Add(CimMethodParameter.Create(
"ReasonCode",
flags[2],
Microsoft.Management.Infrastructure.CimType.UInt32,
CimFlags.None));
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1:51
- This test isn't skipped on non-Windows, but the
-Reasonparameter is only available in the Windows implementation ofStop-Computer(the cmdlet is compiled out under#if !UNIX). This will fail on Unix withNamedParameterNotFound.
It "Should support Reason types" {
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:986
- The
switch (Reason.ToString())block is redundant:Reasonis already a strongly-typed enum with the same values being assigned in each case. Keeping this large string-based mapping increases maintenance risk and makes it easier for the enum values and mapping to drift. Consider replacing the whole switch with a single assignment (for example,flags[2] = (uint)Reason;).
This issue also appears on line 1521 of the same file.
object[] flags = new object[] { 0, 0, 0, 2 };
flags[0] = RestartDelay;
flags[1] = Comment;
flags[2] = Reasons.Planned;
switch (Reason.ToString())
{
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1:49
- This PR adds the new
-RestartDelayparameter, but the test suite only validates-Commentand-Reason. Add at least a basic Windows-only test to ensure-RestartDelaybinds and the cmdlet runs through the testhook path without error.
It "Should support -Comment parameter" -Skip:(!$IsWindows) {
Set-TesthookResult -testhookName $restartTesthookResultName -value $defaultResultValue
$comment = "Testing comment"
Restart-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
}
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1:50
- This PR adds the new
-ShutdownDelayparameter, but the test suite currently only validates-Commentand-Reason. Add at least a basic Windows-only test to ensure-ShutdownDelaybinds and the cmdlet runs through the testhook path without error.
It "Should support -Comment parameter" -Skip:(!$IsWindows) {
Set-TesthookResult -testhookName $stopTesthookResultName -value $defaultResultValue
$comment = "Testing comment"
Stop-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
}
Ryan Yates (kilasuit)
left a comment
There was a problem hiding this comment.
A few additional comments on top of the tests added below.
Can you please file the issue in the PowerShell-Docs repo for documenting these additions.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.
Suppressed comments (6)
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1491
- Same as Restart-Computer:
Reasondefaults to0(Reasons.Other), which makes theflags[2] = Reasons.Planned;initialization ineffective when-Reasonis omitted.
/// <summary>
/// Gets or sets the reason for rebooting the computer.
/// </summary>
[Parameter]
public Reasons Reason { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1629
- Same issue as Restart-Computer: the
default:case overwrites any numeric/combined enum value passed to-Reasonby forcingReasons.Other. Preserve the providedReasonvalue instead.
default:
flags[2] = Reasons.Other;
break;
src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx:164
- Remove trailing whitespace on the closing tag to avoid whitespace-only diffs / potential formatting checks failing.
</data>
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:91
- The new public enum name
Reasonsis very generic for a public API surface (it will show up in metadata/formatting and can be referenced by users). Consider renaming it to something cmdlet-specific (e.g.,ComputerShutdownReason/ComputerRestartReason) to avoid ambiguity and potential future naming collisions.
/// <summary>
/// Supported reasons for restarting or shutting down.
/// </summary>
public enum Reasons : uint
{
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:344
Reasondefaults to0(which isReasons.Other), butProcessRecord()initializes the reason code toReasons.Plannedfirst. Because the subsequent switch will map the defaultOthervalue, the intended default ofPlannedis never effective when-Reasonis omitted.
This issue also appears on line 1487 of the same file.
/// <summary>
/// Gets or sets the reason for rebooting the computer.
/// </summary>
[Parameter]
public Reasons Reason { get; set; }
src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1088
- The
default:case forcesflags[2]toReasons.Other, which will override any numeric/combined enum value a caller passes (e.g.,-Reason 2147483648or[Reasons]0x80040000). SinceReasonis already an enum, the safer default is to preserve the caller-provided value.
This issue also appears on line 1627 of the same file.
default:
flags[2] = Reasons.Other;
break;
There was a problem hiding this comment.
🟡 Changes recommended
Tracker argument propagation lacks meaningful verification, and a public enum member has inconsistent casing.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (2)
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1:47
- These new tests only assert that the cmdlet emits no output. Because
TestStopComputerbypassesInvokeMethod, they do not verify that the supplied comment, delay, or reason reaches the expectedWin32ShutdownTrackerparameter; incorrect ordering or parameter names would still pass. Capture and assert the constructed tracker arguments so the new behavior is actually validated.
It "Should support -Comment parameter" -Skip:(!$IsWindows) {
$comment = "Testing comment"
Stop-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1:46
- These new tests only assert that the cmdlet emits no output. Because
TestStopComputerbypassesInvokeMethod, they do not verify that the supplied comment, delay, or reason reaches the expectedWin32ShutdownTrackerparameter; incorrect ordering or parameter names would still pass. Capture and assert the constructed tracker arguments so the new behavior is actually validated.
It "Should support -Comment parameter" -Skip:(!$IsWindows) {
$comment = "Testing comment"
Restart-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
- Files reviewed: 4/4 changed files
- Comments generated: 1
- Review effort level: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
The tests do not verify that the supplied tracking values reach the CIM invocation.
Review details
Suppressed comments (2)
test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1:47
- These new parameter tests only prove that binding succeeds and the cmdlet emits no output. The enabled test hook bypasses
InvokeMethodand does not expose the constructed CIM arguments, so the tests still pass ifComment,ShutdownDelaySec, orReasonis ignored or forwarded with the wrong value. Extend the hook to capture theTimeout,Comment,ReasonCode, andFlagsparameters, then assert those captured values here.
Stop-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1:46
- These new parameter tests only prove that binding succeeds and the cmdlet emits no output. The enabled test hook bypasses
InvokeMethodand does not expose the constructed CIM arguments, so the tests still pass ifComment,RestartDelaySec, orReasonis ignored or forwarded with the wrong value. Extend the hook to capture theTimeout,Comment,ReasonCode, andFlagsparameters, then assert those captured values here.
Restart-Computer -Comment $comment -ErrorAction Stop | Should -BeNullOrEmpty
- Files reviewed: 4/4 changed files
- Comments generated: 0 new
- Review effort level: Balanced
|
Ryan Yates (@kilasuit) I have made the necessary changes. It was a bit back and forth with copilot reviews :-) |
|
PRASOON KARUNAN V (@kvprasoon) there are these codefactor issues that have been flagged, could you fix these prior to review thanks
|
|
Ryan Yates (@kilasuit) missed those, codefactor is green now. |
|
This pull request has been automatically marked as Review Needed because it has been there has not been any activity for 7 days. |
Ryan Yates (kilasuit)
left a comment
There was a problem hiding this comment.
Looks good enough to me :-)
|
PRASOON KARUNAN V (@kvprasoon) brill - this needs a maintainer to kick off the workflows and reviewed so hopefully this will get picked up soon. |
|
Ryan Yates (@kilasuit) - Thanks for the update |
|
Any update? |
|
Ryan Yates (@kilasuit) can you help in notifying a maintainer to have a look here. |

PR Summary
Recreated closing old PR 17479 which fixes: #4857
PR Context
This PR helps as it adds parameters which helps PowerShell users use Stop-Computer and Restart-Computer more like shutdown.exe.
PR Checklist
.h,.cpp,.cs,.ps1and.psm1files have the correct copyright header