简体   繁体   English

如何使用 Powershell 检查 SQL 服务器版本?

[英]How do I check for the SQL Server Version using Powershell?

What's the easiest way to check for the SQL Server Edition and Version using powershell?使用 powershell 检查 SQL 服务器版和版本的最简单方法是什么?

Just an option using the registry, I have found it can be quicker on some of my systems: 只是使用注册表的一种选择,我发现在某些系统上它可以更快:


$inst = (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
foreach ($i in $inst)
{
   $p = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$i
   (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Edition
   (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Version
}

在此处输入图片说明

Invoke-Sqlcmd -Query "SELECT @@VERSION;" -QueryTimeout 3

http://msdn.microsoft.com/en-us/library/cc281847.aspx

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" "."
$srv.Version
$srv.EngineEdition

Obviously, replace "." 显然,替换为“。” with the name of your instance. 与您的实例的名称。 If you want to see all the methods available, go here . 如果要查看所有可用方法,请转到此处

Hacked up advice from this thread (and some others), this went in my psprofile: 从这个线程(和其他一些线程)窃取了建议,这进入了我的psprofile:

Function Get-SQLSvrVer {
<#
    .SYNOPSIS
        Checks remote registry for SQL Server Edition and Version.

    .DESCRIPTION
        Checks remote registry for SQL Server Edition and Version.

    .PARAMETER  ComputerName
        The remote computer your boss is asking about.

    .EXAMPLE
        PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr 

    .EXAMPLE
        PS C:\> $list = cat .\sqlsvrs.txt
        PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition }

    .INPUTS
        System.String,System.Int32

    .OUTPUTS
        System.Management.Automation.PSCustomObject

    .NOTES
        Only sissies need notes...

    .LINK
        about_functions_advanced

#>
[CmdletBinding()]
param(
    # a computer name
    [Parameter(Position=0, Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [System.String]
    $ComputerName
)

# Test to see if the remote is up
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
    # create an empty psobject (hashtable)
    $SqlVer = New-Object PSObject
    # add the remote server name to the psobj
    $SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName
    # set key path for reg data
    $key = "SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"
    # i have no idea what this does, honestly, i stole it...
    $type = [Microsoft.Win32.RegistryHive]::LocalMachine
    # set up a .net call, uses the .net thingy above as a reference, could have just put 
    # 'LocalMachine' here instead of the $type var (but this looks fancier :D )
    $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)

    # make the call 
    $SqlKey = $regKey.OpenSubKey($key)
        # parse each value in the reg_multi InstalledInstances 
        Foreach($instance in $SqlKey.GetValueNames()){
        $instName = $SqlKey.GetValue("$instance") # read the instance name
        $instKey = $regKey.OpenSubkey("SOFTWARE\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name
        # add stuff to the psobj
        $SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value
        $SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value
        # return an object, useful for many things
        $SqlVer
    }
} else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails
}

Try this 尝试这个

Invoke-SqlCmd -query "select @@version" -ServerInstance "localhost"

屏幕

Check all available method to Get the build number of the latest Cumulative Update / Service Pack that has been installed in SQL Server 检查所有可用方法以获取SQL Server中已安装的最新累积更新/ Service Pack的内部版本号

Here is a version I cobbled together from some sources here and there*. 这是我从这里和那里*的一些来源整理而来的版本。

This version does not hit the registry, does not hit SQL, and doesn't even require that the instance be running. 此版本不会在注册表中运行,也不会在SQL中运行,甚至不需要实例在运行。 It does require that you know the instance name. 它确实要求您知道实例名称。 If you don't know the instance name, you should be able to trivially work it out from this code. 如果您不知道实例名称,则应该可以通过此代码轻松地将其计算出来。

To get this to work, replace "YourInstanceNameHere" with the name of your instance. 要使其正常工作,请将“ YourInstanceNameHere”替换为实例名称。 Don't touch the $ if you do it won't work. 如果您不这样做,请不要触摸$

$ErrorActionPreference = "Stop"
$instanceName = "MSSQL`$YourInstanceNameHere"

$sqlService = Get-Service -Name $instanceName

$WMISQLservices = Get-WmiObject -Class Win32_Product -Filter "Name LIKE 'SQL Server % Database Engine Services'" | Select-Object -Property Name,Vendor,Version,Caption | Get-Unique

foreach ($sqlService in $WMISQLservices)
{
    $SQLVersion = $sqlService.Version
    $SQLVersionNow =  $SQLVersion.Split("{.}")
    $SQLvNow = $SQLVersionNow[0]
    $thisInstance = Get-WmiObject -Namespace "root\Microsoft\SqlServer\ComputerManagement$SQLvNow"  -Class SqlServiceAdvancedProperty | Where-Object {$_.ServiceName -like "*$instanceName*"}  | Where-Object {$_.PropertyName -like "VERSION"}
}

$sqlServerInstanceVersion = $thisInstance.PropertyStrValue

if ($sqlServerInstanceVersion)
{
    $majorVersion = $thisInstance.PropertyStrValue.Split(".")[0]
    $versionFormatted = "MSSQL$($majorVersion)"
}
else
{
    throw "ERROR: An error occured while attempting to find the SQL Server version for instance '$($instanceName)'."
}

$versionFormatted

*I also received help from and help from this this friend of mine https://stackoverflow.com/users/1518277/mqutub and I didn't want it to go uncredited. *我也从我的这个朋友https://stackoverflow.com/users/1518277/mqutub的这个朋友那里得到了帮助,我也不想让它变得不可信。

To add to Brendan's code.. this fails if your machine is 64-bit, so you need to test appropriately. 要添加到Brendan的代码中,如果您的计算机是64位,则此操作将失败,因此您需要进行适当的测试。

Function Get-SQLSvrVer {
<#
    .SYNOPSIS
        Checks remote registry for SQL Server Edition and Version.

    .DESCRIPTION
        Checks remote registry for SQL Server Edition and Version.

    .PARAMETER  ComputerName
        The remote computer your boss is asking about.

    .EXAMPLE
        PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr 

    .EXAMPLE
        PS C:\> $list = cat .\sqlsvrs.txt
        PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition }

    .INPUTS
        System.String,System.Int32

    .OUTPUTS
        System.Management.Automation.PSCustomObject

    .NOTES
        Only sissies need notes...

    .LINK
        about_functions_advanced

#>
[CmdletBinding()]
param(
    # a computer name
    [Parameter(Position=0, Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [System.String]
    $ComputerName
)

# Test to see if the remote is up
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
    $SqlVer = New-Object PSObject
    $SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName
    $base = "SOFTWARE\"
    $key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL"
    $type = [Microsoft.Win32.RegistryHive]::LocalMachine
    $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)
    $SqlKey = $regKey.OpenSubKey($key)
    try {
        $SQLKey.GetValueNames()
    } catch { # if this failed, it's wrong node
        $base = "SOFTWARE\WOW6432Node\"
        $key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL"
        $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName)
        $SqlKey = $regKey.OpenSubKey($key)
    }

        # parse each value in the reg_multi InstalledInstances 
        Foreach($instance in $SqlKey.GetValueNames()){
        $instName = $SqlKey.GetValue("$instance") # read the instance name
        $instKey = $regKey.OpenSubkey("$($base)\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name
        # add stuff to the psobj
        $SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value
        $SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value
        # return an object, useful for many things
        $SqlVer
    }
} else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails
}

All you need is to connect to SQL Server and run this query: 您所需要做的就是连接到SQL Server并运行此查询:

select @@version

This, of course, will work for any client tool. 当然,这将适用于任何客户端工具。

Additionally, this is also available: 此外,这也可用:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

More ways to determine the SQL Server version here: http://support.microsoft.com/kb/321185 在此处确定SQL Server版本的更多方法: http : //support.microsoft.com/kb/321185

Just an expansion of Ben Thul's answer, It loops through a list of all my DB Servers and prints out the current version of the database engine:只是 Ben Thul 答案的扩展,它遍历我所有数据库服务器的列表并打印出数据库引擎的当前版本:

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null

$computers = @(‘XXXX-OMG-DB-01’,’XXXX-PRO-DB-01’,’XXXX-PRO-DB-02’,
               ’XXXX-QAT-DB-01', 'XXXX-TST-DB-01’,'YYYY-PRO-DB-01',
               'YYYY-PRO-DB-02','YYYY-QAT-DB-01','YYYY-QAT-DB-02',
               'YYYY-TST-DB-01','ZZZZ-DEV-DB-01','ZZZZ-DEV-DB-02')

$computers | % { 
    $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $_ 
    if ($null -eq $srv.ComputerNamePhysicalNetBIOS) {
        $s = $_.tostring() + ' is unavailable'
        $s.tostring()
    } else {
        $srv.ComputerNamePhysicalNetBIOS + ' ' +
        $srv.VersionString + ' ' +
        $srv.DatabaseEngineEdition 
    }
 }

Well, here's the old school way, that's easy: 好吧,这是老派的方法,很简单:

sqlcmd -Q "select @@version;"

And here's how I use it from Serverspec : 这是我从Serverspec中使用它的方式

require 'windows_spec_helper'

describe 'MS SQL Server Express' do
  describe service('MSSQLSERVER') do
    it { should be_enabled }
    it { should be_running }
  end
  describe port(1433) do
    it { should be_listening }
  end
  describe command('sqlcmd -Q "select @@version;"') do
    its(:stdout) { should match /Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (X64)/ }
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何知道我的 bacpac 用于哪个版本的 SQL 服务器? (我在 Ubuntu 上使用 SQL Server 2019 express) - How do I know which version of SQL Server my bacpac is for? (I'm using SQL Server 2019 express on Ubuntu ) 如何更改SQL Server实例的版本? - How do I change the version of my SQL Server instance? 如何检查SQL Server的版本? - How to check what is version of SQL Server? 如何使用POWERSHELL脚本获取此SQL输出 - How do I obtain this SQL output using a POWERSHELL script 如何在SQL Server功能的情况下检查null? - How do I check for null in case of a SQL Server function? 如何检查SQL Server datetime列是否为空? - How do I check if a SQL Server datetime column is empty? 如何在没有 SQL DBA 管理员访问权限的情况下使用 powershell 检查服务器中是否存在 SQLAlwaysON? - How to check if SQLAlwaysON is existing in server using powershell without a SQL DBA Admin access? 如何使用 PowerShell 查询 SQL 服务器 - How to query SQL Server using PowerShell 我的 SQL 服务器上有一个检查约束,如何在 c# 中设置检查约束的验证? - I have a check constraint on my SQL server, how do i set a validation for the Check Constraint in c#? 使用这些方法,如何检查此条目是否在 SQL 数据库中? - Using these methods, how do I check if this entry is in a SQL database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM