Skip to content

Commit d62b8ab

Browse files
committed
Replace wmic for user account info on Windows
1 parent 3223c6b commit d62b8ab

File tree

2 files changed

+11
-14
lines changed

2 files changed

+11
-14
lines changed

IPBanCore/Core/Utility/OSUtility.cs

+10-14
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2929
using System;
3030
using System.Collections.Generic;
3131
using System.Diagnostics;
32+
using System.DirectoryServices.AccountManagement;
3233
using System.Globalization;
3334
using System.IO;
3435
using System.Linq;
@@ -277,22 +278,17 @@ private static string HKLM_GetString(string path, string key)
277278

278279
private static void PopulateUsersWindows(Dictionary<string, bool> newUsers)
279280
{
280-
// Windows: WMIC
281-
// wmic useraccount get disabled,name
282-
// FALSE username
283-
// TRUE disabledusername
284-
string output = StartProcessAndWait("wmic", "useraccount get disabled,name");
285-
string[] lines = output.Split('\n').Skip(1).ToArray();
286-
foreach (string line in lines)
281+
using var context = new PrincipalContext(ContextType.Machine);
282+
using var searcher = new PrincipalSearcher(new UserPrincipal(context));
283+
284+
foreach (var result in searcher.FindAll())
287285
{
288-
string trimmedLine = line.Trim();
289-
int pos = trimmedLine.IndexOf(' ');
290-
if (pos >= 0)
286+
if (result is UserPrincipal userPrincipal)
291287
{
292-
string disabled = trimmedLine[..pos].Trim();
293-
string foundUserName = trimmedLine[pos..].Trim();
294-
_ = bool.TryParse(disabled, out bool disabledBool);
295-
newUsers[foundUserName] = !disabledBool;
288+
var foundUserName = userPrincipal.SamAccountName;
289+
// Treat as enabled if null
290+
var isAccountEnabled = userPrincipal.Enabled.GetValueOrDefault(true);
291+
newUsers[foundUserName] = isAccountEnabled;
296292
}
297293
}
298294
}

IPBanCore/IPBanCore.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
4646
<PackageReference Include="NLog" Version="5.3.2" />
4747
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="8.0.0" />
48+
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="8.0.0" />
4849
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
4950
<PackageReference Include="System.Threading.Tasks.Dataflow" Version="8.0.0" />
5051
<PackageReference Include="TaskScheduler" Version="2.11.0" />

0 commit comments

Comments
 (0)