Powershell 收集系统日志信息

Powershell 收集系统日志信息:

  主要是利用smo对象连接数据库,定时(一个小时或者10分钟)将服务器的Application,System,Security 错误信息收集到特定的数据库

  脚本如下(没有过多的注释,将就)

 

 
     
[system.reflection.assembly] :: loadwithpartialname( " Microsoft.sqlserver.smo " ) | out - null
[system.reflection.assembly]
:: loadwithpartialname( " Microsoft.sqlserver.connectioninfo " ) | out - null

# interval
#
$timediff =10
#
$10minutes = new-timespan -Minutes $timediff
#
$10minutesDiff=(get-date) - $10minutes


$timediff = 1
$oneHours = new - timespan - Hours $timediff
$10minutesDiff = (get - date) - $oneHours


$errors = get - eventlog - logname application | where { $_ .EntryType -eq " Error " } | where { $_ .timewritten -gt $10minutesDiff }

$server = " 192.168.1.7 "
$connection = new - object system.data.sqlclient.sqlconnection
$connection .connectionstring = " data source= " + $server + " ;integrated security=true;initial catalog=db1; "
$cmd = $connection .createcommand()
$cmd .commandtype = [system.data.commandtype] :: text
$connection .Open()
foreach ( $errormsg in $errors )
{

# write-host($errormsg.index)
# write-host($errormsg.timewritten)

$insert = " INSERT INTO Applog ([index],[time],[type],[source],[eventid],[message],[servername] )
VALUES ( " + $errormsg .index + " ,' " + $errormsg .timewritten + " ',' " + $errormsg .entrytype + " ',' "
+ $errormsg .source + " ', " + $errormsg .eventid + " ,' " + $errormsg .message + " ',' " + $server + " ') "
# write-host($insert)
$cmd .CommandText = $insert
$cmd .ExecuteNonQuery()
}
$connection .Close()

 表结构如下:

 
     
CREATE TABLE Applog
(
id
INT IDENTITY ( 1 , 1 ) NOT NULL PRIMARY KEY ,
[ servername ] VARCHAR ( 20 ),
[ index ] INT ,
[ time ] VARCHAR ( 20 ),
[ type ] VARCHAR ( 10 ),
[ source ] VARCHAR ( 30 ),
[ eventid ] INT ,
[ message ] VARCHAR ( MAX ),
[ writetime ] DATETIME DEFAULT ( GETDATE ())
)

 希望对大家有所参考。

posted on 2011-06-30 11:32  Henry.Lau 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/Henry1225/archive/2011/06/30/2094303.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值