Good morning.
In PowerShell, Windows 10 executed the following command for performance counter Current Application Pool Uptime:
Get-Counter -Counter '\\khubetsov-pc\APP_POOL_WAS(DefaultAppPool)\Current Application Pool Uptime'
Next, using C # (Net Framework 4.8), I want to get the results of the PowerShell command above:
var ps = PowerShell.Create();
var command = new Command(@"Get-Counter", isScript: false);
var commandParameter = new CommandParameter("Counter", @"\\khubetsov-pc\APP_POOL_WAS(DefaultAppPool)\Current Application Pool Uptime");
command.Parameters.Add(commandParameter);
ps.Commands.AddCommand(command);
var result = ps.Invoke();
However, there is no data in the result variable, the HadErrors property of the PowerShell class instance has a value of True and the following error text is set: The specified counter was not found.
Questions:
It was found that when passing the name of the counter in the current language (in this case, Russian), everything works. Below is a special service:
public static class PerformanceCounterService
{
private static (string Russian, string English) _performanceCounterName = ("текущее время работы пула приложений", "current application pool uptime");
public static float NextValueExt(PerformanceCounter performanceCounter)
{
if (performanceCounter == null) throw new ArgumentNullException(nameof(performanceCounter));
if (performanceCounter.CounterName.ToLower() == _performanceCounterName.English)
{
var separator = @"\";
var instance = string.IsNullOrEmpty(performanceCounter.InstanceName) ? string.Empty : $"({performanceCounter.InstanceName})";
var counterName = CultureInfo.CurrentUICulture.Name == CultureInfo.GetCultureInfo("en-US").Name ? _performanceCounterName.English : _performanceCounterName.Russian;
var path = string.Concat(separator, performanceCounter.CategoryName, instance, separator, counterName);
var computerName = string.Empty;
if (performanceCounter.MachineName != ".")
{
computerName = $"-ComputerName '{performanceCounter.MachineName}'";
}
var script = $"(Get-Counter -Counter '{path}' {computerName}).CounterSamples";
var ps = PowerShell.Create()
.AddScript(script);
var iResult = ps.Invoke();
if (!ps.HadErrors)
{
var psObject = iResult.FirstOrDefault()?.Members["CookedValue"]?.Value ?? default;
return Convert.ToSingle(psObject);
}
}
return performanceCounter.NextValue();
}
}