Skip to content

Adding Comment, Reason and Shutdown/RestartDelay parameters for Stop/Restart-Computer cmdlet - #27721

Open
PRASOON KARUNAN V (kvprasoon) wants to merge 43 commits into
PowerShell:masterfrom
kvprasoon:feat/stopmessage-4857
Open

PRASOON KARUNAN V (kvprasoon) wants to merge 43 commits into
PowerShell:masterfrom
kvprasoon:feat/stopmessage-4857

Conversation

@kvprasoon

Copy link
Copy Markdown
Contributor

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

Copilot AI review requested due to automatic review settings July 23, 2026 17:40
@kvprasoon
PRASOON KARUNAN V (kvprasoon) requested a review from a team as a code owner July 23, 2026 17:40
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@kvprasoon PRASOON KARUNAN V (kvprasoon) changed the title Feat/stopmessage 4857 Adding comment, Reason and RestartDelay parameter for Stop/Restart-Computer cmdlet Jul 23, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ShutdownReasons enum and expose new cmdlet parameters (Comment, Reason, and delay-related parameters).
  • Switch WSMan shutdown/restart invocation to Win32ShutdownTracker and pass Timeout, Comment, ReasonCode, and Flags.
  • Add Pester coverage for the new -Comment and -Reason parameters.

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 valid ValidateRangeAttribute overload and is likely to break compilation. Use a numeric range (as done for RestartDelay) 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.Comment is passed through to the Win32ShutdownTracker call even when the parameter isn't bound. Defaulting it to string.Empty avoids sending null to CIM/WMI and also matches the Restart-Computer implementation.
        [Parameter]
        [ValidateNotNullOrEmpty]
        public string Comment { get; set; }

src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:1536

  • -Reason Planned cannot work for Stop-Computer because the switch doesn't handle the Planned enum name; it falls through to default and sends Other instead.
                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 with ShutdownReasons enum values, but the CIM parameter is declared as UInt32. Passing a boxed enum here can cause runtime type validation failures in CimMethodParameter.Create. Convert the value to uint before adding the parameter.
                    methodParameters.Add(CimMethodParameter.Create(
                        "ReasonCode",
                        flags[2],
                        Microsoft.Management.Infrastructure.CimType.UInt32,
                        CimFlags.None));

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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; }

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: Reason is 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 -Reason parameter is only available in the Windows implementation of Restart-Computer (the cmdlet is compiled out under #if !UNIX). This will fail on Unix with NamedParameterNotFound.
        It "Should support Reason types" {

src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:2547

  • ReasonCode is declared as CimType.UInt32, but flags[2] is populated with the Reasons enum value. Passing the enum object relies on implicit conversion inside MI; cast/convert to uint explicitly 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 -Reason parameter is only available in the Windows implementation of Stop-Computer (the cmdlet is compiled out under #if !UNIX). This will fail on Unix with NamedParameterNotFound.
        It "Should support Reason types" {

src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs:986

  • The switch (Reason.ToString()) block is redundant: Reason is 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 -RestartDelay parameter, but the test suite only validates -Comment and -Reason. Add at least a basic Windows-only test to ensure -RestartDelay binds 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 -ShutdownDelay parameter, but the test suite currently only validates -Comment and -Reason. Add at least a basic Windows-only test to ensure -ShutdownDelay binds 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
        }

@kilasuit Ryan Yates (kilasuit) added the CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log label Aug 2, 2026

@kilasuit Ryan Yates (kilasuit) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@microsoft-github-policy-service microsoft-github-policy-service Bot added the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label Aug 2, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: Reason defaults to 0 (Reasons.Other), which makes the flags[2] = Reasons.Planned; initialization ineffective when -Reason is 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 -Reason by forcing Reasons.Other. Preserve the provided Reason value 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 Reasons is 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

  • Reason defaults to 0 (which is Reasons.Other), but ProcessRecord() initializes the reason code to Reasons.Planned first. Because the subsequent switch will map the default Other value, the intended default of Planned is never effective when -Reason is 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 forces flags[2] to Reasons.Other, which will override any numeric/combined enum value a caller passes (e.g., -Reason 2147483648 or [Reasons]0x80040000). Since Reason is 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;

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 TestStopComputer bypasses InvokeMethod, they do not verify that the supplied comment, delay, or reason reaches the expected Win32ShutdownTracker parameter; 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 TestStopComputer bypasses InvokeMethod, they do not verify that the supplied comment, delay, or reason reaches the expected Win32ShutdownTracker parameter; 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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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 InvokeMethod and does not expose the constructed CIM arguments, so the tests still pass if Comment, ShutdownDelaySec, or Reason is ignored or forwarded with the wrong value. Extend the hook to capture the Timeout, Comment, ReasonCode, and Flags parameters, 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 InvokeMethod and does not expose the constructed CIM arguments, so the tests still pass if Comment, RestartDelaySec, or Reason is ignored or forwarded with the wrong value. Extend the hook to capture the Timeout, Comment, ReasonCode, and Flags parameters, 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

@kvprasoon

Copy link
Copy Markdown
Contributor Author

Ryan Yates (@kilasuit) I have made the necessary changes. It was a bit back and forth with copilot reviews :-)

@kvprasoon PRASOON KARUNAN V (kvprasoon) changed the title Adding comment, Reason and RestartDelay parameter for Stop/Restart-Computer cmdlet Adding Comment, Reason and RestartDelay parameter for Stop/Restart-Computer cmdlet Sep 3, 2026
@kvprasoon PRASOON KARUNAN V (kvprasoon) changed the title Adding Comment, Reason and RestartDelay parameter for Stop/Restart-Computer cmdlet Adding Comment, Reason and Shutdown/RestartDelay parameter for Stop/Restart-Computer cmdlet Sep 3, 2026
@kvprasoon PRASOON KARUNAN V (kvprasoon) changed the title Adding Comment, Reason and Shutdown/RestartDelay parameter for Stop/Restart-Computer cmdlet Adding Comment, Reason and Shutdown/RestartDelay parameters for Stop/Restart-Computer cmdlet Sep 3, 2026
@kilasuit

Copy link
Copy Markdown
Collaborator

PRASOON KARUNAN V (@kvprasoon) there are these codefactor issues that have been flagged, could you fix these prior to review thanks

image

@kvprasoon

Copy link
Copy Markdown
Contributor Author

Ryan Yates (@kilasuit) missed those, codefactor is green now.

@microsoft-github-policy-service microsoft-github-policy-service Bot added the Review - Needed The PR is being reviewed label Sep 25, 2026
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as Review Needed because it has been there has not been any activity for 7 days.
Maintainer, please provide feedback and/or mark it as Waiting on Author

@kilasuit Ryan Yates (kilasuit) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good enough to me :-)

@kilasuit

Copy link
Copy Markdown
Collaborator

PRASOON KARUNAN V (@kvprasoon) brill - this needs a maintainer to kick off the workflows and reviewed so hopefully this will get picked up soon.

@kvprasoon

Copy link
Copy Markdown
Contributor Author

Ryan Yates (@kilasuit) - Thanks for the update

@soroshsabz

Copy link
Copy Markdown

Any update?

@kvprasoon

Copy link
Copy Markdown
Contributor Author

Ryan Yates (@kilasuit) can you help in notifying a maintainer to have a look here.

@kilasuit Ryan Yates (kilasuit) added the Review - Maintainer The PR/issue needs a review from the PowerShell repo Maintainers label Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log Review - Maintainer The PR/issue needs a review from the PowerShell repo Maintainers Review - Needed The PR is being reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restart-Computer and Stop-Computer should take custom message like shutdown.exe

4 participants