잊지 않겠습니다.

indows에서 System의 모든 Monitoring은 WMI를 통해서 가능하다.
WMI를 이용하는 경우, Remote에서 접근이 용의하다는 장점과 Server군의 경우 다양한 속성들을 모두 Monitoring할 수 있다는 큰 장점을 가지고 있다. 또한, 기본적인 WMI의 Query를 통해서 값을 얻는 것이 아닌, .NET에서는 WMI에 대한 Event Handling이 가능하다. 

지정될 수 있는 Event는 http://msdn.microsoft.com/en-us/library/aa394583(VS.85).aspx을 참조.

모니터링 소스는 다음과 같다. 

ConnectionOptions connectionOptions = new ConnectionOptions()
     {
            Authentication = AuthenticationLevel.Default,
            Username = @"UserName",
            Password = @"Password",
            EnablePrivileges = true,
            Impersonation = ImpersonationLevel.Impersonate
      };
            
ManagementScope scope = new ManagementScope(@"\\hyperv\root\cimv2", connectionOptions);
scope.Connect();

//__InstanceCreationEvent : Wmi instance create event
//__InstanceModificationEvent : Wmi instance value modified event
//__InstanceDeletionEvent : Wmi instance delete event
//__InstanceOperationEvent : Wmi instance method call event

WqlEventQuery wQuery = new WqlEventQuery("Select * From __InstanceModificationEvent Within 1 " + "Where TargetInstance ISA 'Win32_PerfFormattedData_Tcpip_NetworkInterface'");

ManagementEventWatcher watcher = new ManagementEventWatcher(scope, wQuery);
watcher.EventArrived += new EventArrivedEventHandler(DisplayWatcherEvent);
watcher.Start();

Console.ReadLine();
            
watcher.Stop();

일반적인 Monitoring Handling과 동일하다. 특징이 나타나는 곳은 오히려 Event 처리기쪽이 더 특징이 나타난다.

private static void DisplayWatcherEvent(object sender, EventArrivedEventArgs e)
{
    foreach(var property in e.NewEvent.Properties)
    {
        if(property.Name == "TargetInstance")
        {
            ManagementBaseObject managementObject = property.Value as ManagementBaseObject;
            if (managementObject == null)
            {
                Console.WriteLine("Data convert is null");
            }
            else
            {
                var bytesPerSec = managementObject.Properties["BytesTotalPersec"].Value;
                var bytesReceivedPersec = managementObject.Properties["BytesReceivedPersec"].Value;
                var bytesSentPersec = managementObject.Properties["BytesSentPersec"].Value;
                string name = managementObject.Properties["Name"].Value.ToString();

                Console.WriteLine("{0}\t{1}\t{2}\t{3}", 
                    name.Substring(0, 4), bytesPerSec, bytesReceivedPersec, bytesSentPersec);
            }
        }
    }
}
특징으로 보이는 것이 EventArrivedEventArgs에서 Property의 Value형태로 WMI Instance의 값이 전달된다는 점이다. 그리고, Performance Counter의 경우에는 이전값, 현재값이 Property의 Name으로 전달되기 때문에 Diff. Monitoring에도 용의하다. 


Posted by Y2K
,

MS SQL Query Script

.NET Framework 2009. 7. 13. 15:37

[System.Reflection.Assembly]::LoadWithPartialName("System")
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Reflection.Assembly]::LoadWithPartialName("System.Data")

$fileContexts = [System.IO.File]::ReadAllLines("c:\mailStore.txt")
$connection = New-Object System.Data.SqlClient.SqlConnection("==THIS IS CONNECTION STRING==");

foreach($fileContext in $fileContexts) {
    $samAccount = $fileContext.Replace("name: ", "").Replace("@mailpush.co.kr", "")
       
    $connection.Open()
    $command = New-Object System.Data.SqlClient.SqlCommand;
    $command.Connection = $connection
    $command.CommandText = "SELECT PhoneNumber, Email From Product WHERE LogonName = '" + $samAccount + "'" + " and ProductStateId = 1"
    $reader = $command.ExecuteReader()

    while($reader.Read())
    {
        $reader.GetSqlString(0).ToString() + "`t" + $reader.GetSqlString(1).ToString() >> c:\output1.txt
    }
    $reader.Close()
    $connection.Close()   
}
[System.Windows.Forms.MessageBox]::Show("Complete!")
notepad.exe "c:\output1.txt"


재미있는 것은 .NET쪽 코드랑 별 다를 것이 없는 코드를 내가 작성하고 있다는 것이다. -_-


Posted by Y2K
,
RSS Feed Script
([xml](new-object System.Net.WebClient).DownloadString("http://blogs.msdn.com/powershell/rss.aspx")).rss.channel.item | format-table title,link


FAST Windows Form
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
$form = new-object Windows.Forms.Form
$form.Text = "My First Form"
$button = new-object Windows.Forms.Button $button.text="Push Me!"
$button.Dock="fill"
$button.add_click({$form.close()})
$form.controls.add($button)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

:여기서 중요한 코드는 첫줄. Assembly의 동적 Loading이 저렇게 쉽게 가능하다는 것이 가장 멋진 일이다.

ERROR LOG FINDER
dir $env:windir\*.log | select-string -list error | format-table path,linenumber –autosize
Posted by Y2K
,