Powershell如何查询多个类并写入SQL表 [英] Powershell How to query multiple classes and write in to SQL Table

查看:236
本文介绍了Powershell如何查询多个类并写入SQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不太了解Powershell和sql,我花了整整一个星期的时间来整理一个脚本,该脚本可以完成很多工作,但是我需要在它的扩展方面有所帮助.它可以从同一类中检索多个值,并插入这些值.我需要做的是能够从其他类中检索值并将结果插入到适当的列中.任何帮助/建议将不胜感激.

Not knowing Powershell very well and indeed sql it's taken me all week to piece together a script thatkind of works but I need help expanding on it. It works for retrieving more than 1 value from the same class and inserts the values. What I need to do is to be able to retrieve values from other classes and insert the result in to the appropriate column. Any help / advice would be so appreciated.

$servernames = Get-WmiObject -computername Anycompname -class win32_ComputerSystem |     Select Name, Manufacturer

# Open Connection
$conn = New-Object System.Data.SqlClient.SqlConnection
$connectionString = "Server=;Database=;user=;pwd=;"
$conn.ConnectionString = $connectionString
$conn.Open()

# Create the Command object to execute the queries
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $conn
$cmd.CommandType = [System.Data.CommandType]::Text

# Write Data
foreach ($servername in $servernames)
{
# Compose Query for this $servername - watch the single quotes for string values!!
$query = "INSERT INTO dbo.U_Server (ServerName, OSVersion) VALUES ('" +        $servername.Name + "', '" + $servername.Manufacturer + "')"

# Uncomment next line to display query for checking
$query 

# Setup Command
$cmd.CommandText = $query

# Execute Command to insert data for this $drive
$result = $cmd.ExecuteNonQuery() 
}

# Tidy Up 
$conn.Close()

推荐答案

只需在foreach循环中获取其他WMI对象,并根据需要不断添加到您的插入字符串中即可.

Just get the other WMI object(s) in the foreach loop and keep adding to your insert string as needed.


foreach ($servername in $servernames)
{
##  Get other WMI info as needed here.
$os = Get-WmiObject -class win32_operatingsystem –computername $servername.Name
$processors = Get-WmiObject Win32_Processor -computername $servername.Name

# Compose Query for this $servername 
$query = "Insert Into dbo.U_Server (ServerName, OSVersion, OSName, OSServicePack) Values 
('$($servername.Name)', '$($servername.Manufacurer)', ‘$($os.Caption)’, ‘$($os.ServicePackMajorVersion)’ )"

##  The rest of your foreach loop follows

}  ##  End of foreach

这篇关于Powershell如何查询多个类并写入SQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆