首页 > 数据库 >通过PowerShellPlus示例脚本学习PowerShell-连接SQLServer数据库

通过PowerShellPlus示例脚本学习PowerShell-连接SQLServer数据库

时间:2023-11-19 13:01:31浏览次数:31  
标签:set false 示例 ## xxx SQLServer Accept SQL PowerShellPlus

## =====================================================================
## Title       : Connect-MSSQL-IPSQLAuth
## Description : Connect to $ServerName using SQL Server authentication.
##               This connection is not encrypted. 
##               User ID and Password are transmitted in plain text.
## Author      : Idera
## Date        : 1/28/2009
## Input       : -ipAddress < xxx.xxx.xxx.xxx | xxx.xxx.xxx.xxx\instance >
##               -verbose 
##               -debug	
## Output      : Database names and owners
## Usage			: PS> .\Connect-MSSQL-IPSQLAuth -ipAddress 127.0.0.1 -verbose -debug
## Notes 		: In SQL Server 2008, you must enable SQL Authentication and
##               the SQL account you are using (sa is disabled by default)
##	Tag			: MSSQL, connect, IP, SQL Authentication
## Change Log  :
##  4/1/2009 - Revised SMO Assemblies 
##  4/1/2009 - Added input prompts and write-verbose statements
## =====================================================================
 
param
(
  	[string]$ipAddress = "$(Read-Host 'IP Address' [e.g. 127.0.0.1])",
	[switch]$verbose = $true,
	[switch]$debug = $false
)

function main()
{
	if ($verbose) {$VerbosePreference = "Continue"}
	if ($debug) {$DebugPreference = "Continue"}

	Write-Verbose "Connect to $ServerName using SQL Server authentication..."
	Connect-MSSQL-IPSQLAuth $ipAddress
}

function Connect-MSSQL-IPSQLAuth($ipAddress)
{
	trap [Exception] 
	{
		write-error $("TRAPPED: " + $_.Exception.Message);
		continue;
	}
	
	# Load SMO assemblies
	[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.Management.Common" );
	[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.SmoEnum" );
	[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.Smo" );
	[void][reflection.assembly]::LoadWithPartialName( "Microsoft.SqlServer.SmoExtended " );
	
	$smoServer = new-object( 'Microsoft.SqlServer.Management.Smo.Server' ) ($ipAddress)

	# The connection will use SQL Authentication, so set LoginSecure to FALSE
	$smoServer.ConnectionContext.set_LoginSecure($FALSE)
	
	# Pop a credentials box to get User Name and Password
	$LoginCredentials = Get-Credential
	
	# If the user does not specify a domain, UserName will begin with a slash.
	# Remove leading slash from UserName
	$Login = $LoginCredentials.UserName -replace("\\","")
	
	# Set properties of ConnectionContext
	$smoServer.ConnectionContext.set_EncryptConnection($FALSE)
	$smoServer.ConnectionContext.set_Login($Login)
	$smoServer.ConnectionContext.set_SecurePassword($LoginCredentials.Password)
	
	# The connection is established the first time you access the server's properties.
	cls
	Write-Host Your connection string contains these values:
	Write-Host
	Write-Host $smoServer.ConnectionContext.ConnectionString.Split(";")
	Write-Host
	
	# List info about databases on the instance.
	Write-Host "Databases on $ipAddress "
	Write-Host
	foreach ($Database in $smoServer.Databases) 
	{
		write-host "Database Name : " $Database.Name
		write-host "Owner         : "	$Database.Owner
		write-host
	}
}

main

本脚本使用IP地址,使用SQL验证登录到SQLServer服务器。

57行有一个新命令Get-Credential,命令主要是弹出框输入用户名和密码进行验证。信息如下:

SYNTAX
    Get-Credential [[-Credential] <pscredential>] [<CommonParameters>]

    Get-Credential [[-UserName] <string>] [-Message <string>] [-Title <string>] [<CommonParameters>]


PARAMETERS
    -Credential <pscredential>

        Required?                    false
        Position?                    0
        Accept pipeline input?       false
        Parameter set name           CredentialSet
        Aliases                      None
        Dynamic?                     false
        Accept wildcard characters?  false

    -Message <string>

        Required?                    false
        Position?                    Named
        Accept pipeline input?       false
        Parameter set name           MessageSet
        Aliases                      None
        Dynamic?                     false
        Accept wildcard characters?  false

    -Title <string>

        Required?                    false
        Position?                    Named
        Accept pipeline input?       false
        Parameter set name           MessageSet
        Aliases                      None
        Dynamic?                     false
        Accept wildcard characters?  false

    -UserName <string>

        Required?                    false
        Position?                    0
        Accept pipeline input?       false
        Parameter set name           MessageSet
        Aliases                      None
        Dynamic?                     false
        Accept wildcard characters?  false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).


INPUTS
    None


OUTPUTS
    System.Management.Automation.PSCredential


ALIASES
    None

标签:set,false,示例,##,xxx,SQLServer,Accept,SQL,PowerShellPlus
From: https://blog.51cto.com/u_3353175/8472028

相关文章

  • Tcpdump使用示例
    这里收集了一些实用的tcpdump使用示例,使用它们可提升您的网络故障排除和安全测试能力。熟练掌握下面的tcpdump使用示例,可以帮助我们更好的了解自己的网络。了解tcpdump是一项基本技能,不仅对于系统管理员、网络工程师或安全专业人员,对于自己部署玩的一些服务器来说,也会派上......
  • Halo2简单示例
    Halo2简介[[Halo2]]是使用[[Rust]]语言开发,基于[[PLANK算法]]的,一款开源交互式([[STARKs]]),[[零知识证明(ZKP)]]的[[证明系统]]。GitHub仓库地址:halo2不同于普通的开发框架,Halo2中的功能开发称为电路(Circuit)开发,电路开发使用表格来设计并记录运算,并包含一系列的约束来验证......
  • 通过PowershellPlus示例脚本学习PowerShell-CheckDB
    ##=====================================================================##Title:CheckDB-MSSQL-UsingADO##Description:RunaDBCCagainstspecifiedserverinstanceanddatabase##Author:Idera##Date:9/1/2008##Input:-......
  • netcore 间隔时长修改参数 示例
    usingSystem;usingSystem.Threading.Tasks;classProgram{privatestaticintyourParameter=0;staticasyncTaskMain(){while(true){//等待5分钟awaitTask.Delay(TimeSpan.FromMinutes(5));//在这......
  • Mutiny Uni阻塞操作变响应式的方法示例
    以下代码片段为模拟一个这样的操作:在多台服务器上下载文件列表内的文件。其中,获取服务器、获取文件列表、在服务器执行下载操作均为阻塞方法。importcn.hutool.core.collection.CollUtil;importio.quarkus.test.junit.QuarkusTest;importio.smallrye.mutiny.Multi;impor......
  • sqlserver数据库中的mdf文件太大,表空间分析和表空间释放
    原文地址:https://tool.4xseo.com/a/8890.html查询数据库的大小:EXECsp_spaceused为了保证查询结果的实时性,推荐使用@updateusage参数来确保统计数据是最新的:EXECsp_spaceused@updateusage=N'TRUE';具体查询某个表的大小:EXECsp_spaceused't_table'分析查询数......
  • SQLSERVER 日期和时间
    日期和时间数据类型数据类型格式范围精确度存储大小(字节)用户定义的秒的小数部分精度时区偏移量timehh:mm:ss[.nnnnnnn]00:00:00.0000000到23:59:59.9999999100纳秒3到5是否dateYYYY-MM-DD0001-01-01到31.12.991天3否否smalldatetimeYYYY-MM-DD......
  • sqlserver-cdc 自动清理时间设定
    1、默认cdc记录清理时间查询EXECsys.sp_cdc_help_jobs 2、修改cdc记录清理时间EXECUTEsys.sp_cdc_change_job@job_type=N'cleanup',@retention=4320; ......
  • sqlserver登录名和用户名之间的关系
    SQLServer创建登录名和用户名【详细介绍】_ssms可视化新建用户-CSDN博客一、登录名与用户名首先,咱们先来聊聊:数据库登陆名和数据库用户名之间的关系。数据库登陆名和数据库用户名是有差别的,在一个数据库中是一一相对应的关系。一个经典的比喻:如果把数据库比作一个大厦,那么数据......
  • SqlServer中获取数据库中每个表的行数
    SqlServer中获取数据库中每个表的行数CREATETABLE#RowCounts(NumberOfRowsBIGINT,TableNameVARCHAR(128))EXECsp_MSForEachTable'INSERTINTO#RowCountsSELECTCOUNT_BIG(*)ASNumberOfRows,''?''asTableNameFROM?'SELECTTableName,Numbe......