From d59627f9ae51c90f405efc3def38e134d4164d88 Mon Sep 17 00:00:00 2001 From: charub Date: Fri, 3 Mar 2017 11:13:42 -0800 Subject: [PATCH] Fix New-LocalUser cmdlet to roll back user in case of user attributes assignment failure. Resolving #3242 At this point, user account is created even if user attributes assignment (like setting password) fails. The cmdlet throws a non-terminating error but ends up creating the user. This behavior is confusing. As per the changes, the localuser account will be rolled back in case of failure in user attributes assignment. --- .../LocalAccounts/Sam.cs | 8 ++++++++ ....Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index 692756b04..20f582b69 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -1271,6 +1271,14 @@ namespace System.Management.Automation.SecurityAccountsManager }, userHandle); } + catch (Exception) + { + if (IntPtr.Zero != userHandle) + { + SamApi.SamDeleteUser(userHandle); + } + throw; + } finally { if (buffer != IntPtr.Zero) diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 index 73c6ec7ab..d0bee20c4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 @@ -348,6 +348,17 @@ try { VerifyFailingTest $sb "InvalidPassword,Microsoft.PowerShell.Commands.NewLocalUserCommand" } + It "User should not be created when invalid password is provided" { + $sb = { + New-LocalUser TestUserNew1 -Password (ConvertTo-SecureString ("A"*257) -AsPlainText -Force) + } + VerifyFailingTest $sb "InvalidPassword,Microsoft.PowerShell.Commands.NewLocalUserCommand" + $sb1 = { + Get-LocalUser TestUserNew1 + } + VerifyFailingTest $sb1 "UserNotFound,Microsoft.PowerShell.Commands.GetLocalUserCommand" + } + It "Can set UserMayNotChangePassword" { $result = New-LocalUser TestUserNew1 -NoPassword -UserMayNotChangePassword