Привет всем. Я новичок в программировании на C# и .NET. Я пытаюсь взять сценарий PowerShell и создать агент, выполняющий аналогичную функцию. Агент компилируется и устанавливается правильно, а также записывает выходные данные команд powershell в файл журнала. Проблема в том, что я не получаю доступ к значениям, а журнал распечатывает объект? Как я могу получить доступ к значениям? Заранее спасибо и будьте осторожны с моей элементарной попыткой.
Моя ссылка на документацию, которую я использовал:
https://learn.microsoft.com/en-us/ dotnet/api/system.management.automation.powershell?view=powershellsdk-7.4.0
Вывод файла журнала:
Время выполнения: 2.10.2024 3:49: 16:00 Запущена ловушка пропускной способности...System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]
Код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Management.Automation;
namespace SBC_Agent
{
public partial class Service1 : ServiceBase
{
Timer timer = new Timer(); // name space(using System.Timers;)
private Timer _audittimer;
private string auditFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\Audit";
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in milliseconds
timer.Enabled = true;
_audittimer = new Timer();
_audittimer.Interval = 60000;
_audittimer.Elapsed += new ElapsedEventHandler(OnElapsedAuditTime);
_audittimer.Enabled = true;
Directory.CreateDirectory(Path.GetDirectoryName(auditFilePath));
}
private void OnElapsedAuditTime(object source, ElapsedEventArgs e)
{
RunPowerShellCommands();
}
private void BandwidthTrap()
{
try
{
using (System.Management.Automation.PowerShell psInstance = System.Management.Automation.PowerShell.Create())
{
//psInstance.AddScript("Get-WmiObject -Class win32_ip4routetable | where {$_.destination -eq \"0.0.0.0\"} | select -ExpandProperty InterfaceIndex | select -First 1");
psInstance.AddScript("Get-WmiObject -Class win32_ip4routetable");
var int_index = psInstance.Invoke();
//var ifIndex = "InterfaceIndex=" + int_index;
using (StreamWriter writer = new StreamWriter(auditFilePath, true))
{
writer.WriteLine("Execution Time: " + DateTime.Now.ToString() + " Launched Bandwidth Trap..." + int_ndex);
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("Powershell Service Error: " + ex.Message, EventLogEntryType.Error);
using (StreamWriter writer = new StreamWriter(auditFilePath, true))
{
writer.WriteLine("Error: " + ex.Message);
writer.WriteLine("StackTrace: " + ex.StackTrace);
}
}
}
private void RunPowerShellCommands()
{
try
{
BandwidthTrap();
/*
using (System.Management.Automation.PowerShell psInstance = System.Management.Automation.PowerShell.Create())
{
psInstance.AddScript("Get-Process");
var results = psInstance.Invoke();
using (StreamWriter writer = new StreamWriter(auditFilePath, true))
{
writer.WriteLine("Execution Time: " + DateTime.Now.ToString());
foreach (var result in results)
{
writer.WriteLine(result.ToString());
}
writer.WriteLine();
}
}
*/
}
catch (Exception ex)
{
EventLog.WriteEntry("Powershell Service Error: " + ex.Message, EventLogEntryType.Error);
using (StreamWriter writer = new StreamWriter(auditFilePath, true))
{
writer.WriteLine("Error: " + ex.Message);
writer.WriteLine("StackTrace: " + ex.StackTrace);
}
}
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
WriteToFile("Service is recall at " + DateTime.Now);
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
//Create a file to write to
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
Исходный сценарий:
$HOSTNAME=hostname
$RXKEY="bandwidth_rx_trap"
$TXKEY="bandwidth_tx_trap"
$ifIndex = Get-WmiObject -Class win32_ip4routetable | where {$_.destination -eq "0.0.0.0"} | select -ExpandProperty InterfaceIndex | select -First 1
$ifIndex = "InterfaceIndex=" + $ifIndex
$nic_name = Get-WmiObject -Class win32_networkadapterconfiguration -Filter $ifIndex | select -ExpandProperty Description
$nic = [System.Net.NetworkInformation.Networkinterface]::GetAllNetworkInterfaces() | where {($_.description -eq $nic_name) -and ($_.operationalstatus -eq "up")}
for ($i=1; $i -le 5; $i++){
$bytesSent = 0
$bytesReceived = 0
$stats = $nic.GetIPv4Statistics()
$bytesSent = $stats.BytesSent
$bytesReceived = $stats.BytesReceived
$bytesSentSum = $bytesSentSum + $bytesSent
$bytesReceivedSum = $bytesReceivedSum + $bytesReceived
Start-Sleep 1
}
$TXAVG=[math]::round($bytesSentSum/5/1024,0)
$RXAVG=[math]::round($bytesReceivedSum/5/1024,0)
Подробнее здесь: https://stackoverflow.com/questions/790 ... ll-objects
Powershell SDK получает доступ к значениям объектов Powershell? ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Сортировка массива объектов по значениям даты и времени в формате Y-n-d H:i:s [дубликат]
Anonymous » » в форуме Php - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-