Invoke-Sqlcmd无法运行。

11

我有一个PowerShell脚本,检查运行它的服务器的CPU使用率,如果超过一定阈值,就会运行SQL存储过程并发送电子邮件。

该脚本在我的开发服务器上以最新版本的PowerShell正确运行。但是,在需要获取CPU值的生产服务器上运行Invoke-Sqlcmd命令时遇到了问题。例如可以称为"LIVESERVER"。 它正在运行PowerShell 2.0,我认为这就是问题所在:

The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

由于这是业务关键型服务器,我不想对其进行任何更改(除非更新PowerShell而无需重新启动等操作非常简单)。

是否可能从我的开发服务器运行我的脚本并指定要获取CPU数据的服务器?我不确定如何编写语法以实现此目的。

以下是我的脚本:

# Email 
$recipients = @("Ricky <ricky@email.com>")

# Loop 20 times
for ($i= 1; $i -le 20; $i++) {
    # Find CPU average usage percentage for given time period
    $cpuutil = (Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 20 |
               select -ExpandProperty countersamples |
               select -ExpandProperty cookedvalue |
               Measure-Object -Average).Average

    # Display average CP output
    $cpuutil

    # If CPU average percentage is higher than given value, run stored procedure and
    # e-mail to notify
    if ($cpuutil -ge 60) {
        Invoke-Sqlcmd -Query "SELECT * FROM [Vehicle].[dbo].[tblIndicator]" -ServerInstance "LIVESERVER"
    }

    if ($cpuutil -ge 60) {
        Send-MailMessage -From "serverchecks@email.com" -To $recipients -Body "SP Ran" -Subject "Stored Procedure" -Dno onSuccess, onFailure -SmtpServer 111.1.1.111
    } else {
        Start-Sleep -s 10
    }
}

这个回答解决了你的问题吗?Invoke-Sqlcmd' is not recognized as the name of a cmdlet - Michael Freidgeim
5个回答

14

如果导入模块失败,则需要先运行安装模块。SSMS或SSDT的安装不会默认包括sqlserver模块。

install-module sqlserver
update-module sqlserver
import-module sqlserver

11

这应该有助于您的调试!

if (-not (Get-Command Invoke-Sqlcmd -ErrorAction SilentlyContinue)) {
    Write-Error "Unabled to find Invoke-SqlCmd cmdlet"
}

if (-not (Get-Module -Name SqlServer | Where-Object {$_.ExportedCommands.Count -gt 0})) {
    Write-Error "The SqlServer module is not loaded"
}

if (-not (Get-Module -ListAvailable | Where-Object Name -eq SqlServer)) {
    Write-Error "Can't find the SqlServer module"
}

Import-Module SqlServer -ErrorAction Stop

8

7

PowerShell v2不会自动加载模块,因此需要手动加载相关的模块或snapins:

Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100

[Source]


那对我有用,我之前可能加载了错误的 snapin,因为我尝试类似的操作时出现了错误。谢谢! - Ricky
如果您仍然遇到错误并且未在计算机上安装Sql Server,则可以安装SqlServer Powershell。这对我有用。 - Umut Çömlekçioğlu

-2

花了将近一个小时解决这个问题。当我使用MS Build运行脚本时,出现了以下错误信息。

SQLCMD:未将“SQLCMD”识别为cmdlet、函数、脚本文件或可运行程序的名称。

最终我发现,在SQL服务器安装后重新启动Windows服务器就解决了问题。现在我的脚本可以顺利运行了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接