编码/ Powershell非常新,但我的项目非常接近。尝试自动连接到我的SQL DB并导出到CSV(如果可能的话,可以excel)。我成功连接到数据库并获取准确的信息,但我似乎无法将数据导出到文件中。这是我的代码:
$DBServer = "E2\E2SQL"
$databasename = "****"
$UID = "sa"
$pass = "*****"
$Connection = new-object system.data.sqlclient.sqlconnection #Set new object to connect to sql database
$Connection.ConnectionString ="server=$DBServer;database=$databasename;User Id=$UID;password=$pass;trusted_connection=False" # Connectiongstring setting for local machine database with window authentication
Write-host "Connection Information:" -foregroundcolor yellow -backgroundcolor black
$Connection #List connection information
### Connect to Database and Run Query
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand #setting object to use sql commands
$SqlQuery = @"
SELECT JobNo FROM Online
"@
$Connection.open()
Write-host "Connection to database successful." -foregroundcolor green -backgroundcolor black
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$Connection.Close()
$DataSet.Tables[0]
export-csv -path "C:\Users\BOB\Desktop\TEST.csv" -NoTypeInformation
当我运行代码时,正确的信息显示!但是,我得到一个弹出窗口,在命令管道位置1处显示" cmdlet Export-Csv - 提供以下参数的值:InputObject"我一直试图解决这个问题,但一直没有成功。知道这个错误是什么或如何解决它?如何将数据写入我的CSV(如果可能的话,还是excel)? 谢谢大家
答案 0 :(得分:0)
更短的做法:
$output ="C:\Users\BOB\Desktop\TEST.csv"
$DBServer = "E2\E2SQL"
$databasename = "****"
$UID = "sa"
$pass = "*****"
$SqlQuery = @"SELECT JobNo FROM Online"@
invoke-sqlCmd -serverinstance @DBServer -database $databasename
-Username $UID -Password $pass -Query $SqlQuery | Export-Csv $output