0

我正在编写一些 Powershell 脚本来管理 SQL Server。当我创建我的 SMO 对象时,我会进行测试以查看是否可以列出我的数据库。如果是这样,那么我假设我已连接并调用一个函数(通过包含的文件),该函数具有Invoke-Sqlcmd导致我的数据库断开连接或其他东西的函数。但是,如果我直接在脚本中运行调用命令,它就可以正常工作。

查看提供的代码,我的输出如下:

我已连接
$SqlServer 不可联系
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null 
$ErrorActionPreference = "Stop"    
Import-Module 'sqlps' -DisableNameChecking #load all of SMO

$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition - 
Parent
try {
    ("$ScriptDirectory\_HRbackup.ps1")
    ("$ScriptDirectory\_HRprinter.ps1")
    ("$ScriptDirectory\_HRbody.ps1")
} catch {
    Write-Host "Error while loading supporting PowerShell Scripts" 
} 

$ServerList = $env:COMPUTERNAME    
$SqlServer = New-Object ('Microsoft.SqlServer.Management.Smo.Server') 
$ServerList # add server list    
try {  
    $databases = $SqlServer.Databases

    if ($databases.Count -gt 0) {
        Write-Host "I am connected" 
        Backup-Html
    } else {
        $login = Get-Credential -Message 'Please prov#ide your SQL 
Credentials'

        $SqlServer.ConnectionContext.LoginSecure = $false
        $SqlServer.ConnectionContext.Login = $login.UserName
        $SqlServer.ConnectionContext.set_SecurePassword($login.Password)
        $SqlServer.ConnectionContext.connect()
    }
} catch {    
    $WarningPreference = 'continue'  
    Write-Warning "$SqlServer is not contactable"   
    #$SqlServer.ConnectionContext.Disconnect()  
} finally {    
    $SqlServer.ConnectionContext.Disconnect()    
} 

以下是 的内容Backup-Html

$Query = "select  top 5 a.server_name, a.database_name, 
 backup_finish_date, a.backup_size,
                CASE a.[type] -- Let's decode the three main types of 
 backup here
                    WHEN 'D' THEN 'Full'
                    WHEN 'I' THEN 'Differential'
                    WHEN 'L' THEN 'Transaction Log'
                    ELSE a.[type]
                END as BackupType
                -- Build a path to the backup
                ,'\\' + 
                -- lets extract the server name out of the recorded 
server and instance name
                CASE
                    WHEN patindex('%\%',a.server_name) = 0  THEN 
a.server_name
                    ELSE 
substring(a.server_name,1,patindex('%\%',a.server_name)-1)
                END 
                -- then get the drive and path and file information
                + '\' + replace(b.physical_device_name,':','$') AS 
 '\\Server\Drive\backup_path\backup_file'
                from msdb.dbo.backupset a join msdb.dbo.backupmediafamily 
 b
                    on a.media_set_id = b.media_set_id
                where a.database_name Like 'Easy%'
                order by a.backup_finish_date desc"

#Use SQLCmd to execute the query on the server
Invoke-Sqlcmd -ServerInstance $SQLServer -Query $Query
4

0 回答 0