查詢系統當下的 Process 並存到 DB

Param
(
    [string]$cnn="Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI",
    [int]$period=300
)
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = $cnn
$sqlConnection.Open()

$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandText="
if not exists(select * from sys.objects where name=’tbProcess’ and type=’u’)
    create table tbProcess(pk int identity primary key,
    id int,
    name nvarchar(500),
    path nvarchar(1000),
    pollingTime datetime2(3) default(sysdatetime())
    )
"
$sqlCommand.Connection=$sqlConnection
$sqlCommand.ExecuteNonQuery()

$sqlCommand.CommandText="insert tbProcess(id,name,path) values(@id,@name,@path)"
$sqlPar=new-object Data.SqlClient.SqlParameter("id",[System.Data.SqlDbType]::Int)
$sqlCommand.Parameters.Add($sqlPar) | Out-Null
$sqlPar2=new-object System.Data.SqlClient.SqlParameter("name",[System.Data.SqlDbType]::NVarChar,500)
$sqlCommand.Parameters.Add($sqlPar2) | Out-Null
$sqlPar3=new-object System.Data.SqlClient.SqlParameter("path",[System.Data.SqlDbType]::NVarChar,1000)
$sqlCommand.Parameters.Add($sqlPar3) | Out-Null

$d=get-date
for([int]$i=0;$i -le $period;$i++ )
{
    $processes=Get-Process
    foreach($process in $processes)
    {
        $sqlCommand.Parameters[0].Value=$process.Id
        $sqlCommand.Parameters[1].Value=$process.Name
        if($process.Path -eq $null)
        {
            $sqlCommand.Parameters[2].Value=""
        }
        else
        {
            $sqlCommand.Parameters[2].Value=$process.path
        }
        $sqlCommand.ExecuteNonQuery() | Out-Null
    }
    [System.Threading.Thread]::Sleep(1000)
    Write-Host $i
}
$sqlConnection.Close()

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: