Powershell & SQL

一、使用Powershell插入数据到SQL中

  1、方法一

 1 $ServerName=xxx
 2 $Database=xxx
 3 $UserID=xxx
 4 $Pwd=xxx
 5 $conn=new-object System.Data.SqlClient.SQLConnection
 6 $ConnectionString = "Server=$ServerName;Database=$Database;User ID=$UserID;Password=$pwd;Trusted_Connection=False;Connect Timeout=6000"
 7 $conn.ConnectionString=$ConnectionString 
 8 $conn.Open()
 9 
10 $Query="insert into 表名称(字段名, EventTime, EventType, EventId, Message) values(数值,N'$EventTime',N'$EventType',N'$EventId',N'$Message')" 
11  $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) 
12  $cmd.CommandTimeout=6000
13  $cmd.ExecuteNonQuery()
14  $conn.close()
View Code

 

  2、方法二

 1 $Database = "xxx"
 2 $Server = "xxx"
 3 $Connection = New-Object System.Data.SQLClient.SQLConnection
 4 $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
 5 $Connection.Open()
 6 $Command = New-Object System.Data.SQLClient.SQLCommand
 7 $Command.Connection = $Connection
 8 
 9 
10 $insert="insert into 表名称(字段名,EventTime, EventType,EventSource, EventId, Message,RecordId) values(数值,N'$EventTime',N'$EventType',N'$TaskDisplayName',N'$EventId',N'$Message',N'$RecordId')" 
11   $cmd1=new-object system.Data.SqlClient.SqlCommand($insert,$Connection) 
12 $cmd1.CommandTimeout=6000
13 $cmd1.ExecuteNonQuery()
14 $Connection.Close()
View Code

 

二、使用Powershell从数据库中获取数据

  

 1 $Database = "xxx"
 2 $Server = "xxx"
 3 $ServerName="xxx"
 4 $Connection = New-Object System.Data.SQLClient.SQLConnection
 5 $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
 6 $Connection.Open()
 7 $Command = New-Object System.Data.SQLClient.SQLCommand
 8 $Command.Connection = $Connection
 9  
10 Add-PSSnapin SqlServerCmdletSnapin100
11 Add-PSSnapin SqlServerProviderSnapin100
12 
13 $cmd=Invoke-Sqlcmd -ServerInstance $server -Database $Database -Query "select MAX(recordid) from [$Database].dbo.[$table] where [ServerName]='$serverName'"
14 $max=$cmd.column1
View Code

 

转载于:https://www.cnblogs.com/thescentedpath/p/PowershellSQL.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值