Powershell Try Catch invoke-sqlcmd

前端 未结 3 1374
耶瑟儿~
耶瑟儿~ 2020-12-17 21:57

I am having problems catching an error in PowerShell when a connection fails to a SQL Server using Invoke-Sqlcmd. This is some generic code to demonstrate the issue:

<
3条回答
  •  时光说笑
    2020-12-17 22:20

    Try

    CLS
    $server = "Localhost/fake"
    try
    {
        Invoke-Sqlcmd -Query "SELECT DB_NAME() as [Database]" -Server $server
    }
    catch
    {
        $_ | Out-Null
        Write-Host "Error connecting to server " $server
    }
    

    This will capture the error and redirect it to null and display your write-host

提交回复
热议问题