简体   繁体   中英

Connecting powershell to SQL Server

I'm quite new to both SQL and Power shell , but I want to run a script which pulls data from a server within SQL - Any advice on where to start?

I tried using this as a starting point, but got no luck as it doesn't like my credentials even though they are correct

Test:

SqlConnection -ServerName 'END-HDSQ02\DEV4' -DatabaseName 'tbl_cert_expiry' -Credential (Get-Credential)

EDIT: Since Powershell V2, you are required to manually load the necessary Snap-Ins; Powershell - Invoke-Sqlcmd unable to run

Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100

This is what we use to query a SQL View;

[string] $Server= "ServerName"
[string] $Database = "DatabaseName"
[string] $SQLQuery= $("SELECT * FROM schema.TableView order by column")


$data = Invoke-Sqlcmd -ServerInstance $server -Database $database -Username $username -Password $value1 -Query $SQLQuery

Obviously you'll need to pass the connecting user and password as well, but I've omitted them from my example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM