使用PowerShell脚本更新数据库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/allenwdj/article/details/72302978

在很多时候,我们在发布程序的时候,都需要更新数据库,以前我的做法是,手动去执行更新脚本,但是后来思考,我们是不是可以做的更加自动化点,于是就考虑用powershell脚本来执行数据库的更新。

脚本如下:

chcp 65001

$sqlInstance = "localhost"
$userName = "sa"
$password = "password"
$path = Split-Path -Parent $MyInvocation.MyCommand.Definition
$scriptPath = $path + "\ExecuteSQLScript\"
$isExists = Test-Path $scriptPath
if($isExists){
    $hasFiles = $false;
    Write-Output "开始执行更新脚本..."
    $scriptFiles = Get-ChildItem -Path $scriptPath -Include "*.sql" -Recurse  | Sort-Object Name
    foreach($file in $scriptFiles)
    {
        $hasFiles = $true;
        Write-Output "正在执行$file..."
        try
        {
            Invoke-Sqlcmd -ServerInstance $sqlInstance -Username $userName -Password $password -InputFile $file -QueryTimeout 3600
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            Write-Error "执行数据库脚本$($file)时出错:$($ErrorMessage)"
        }
    }
    if($hasFiles)
    {
        Write-Output "执行完毕。`r`n"
    }
    else
    {
        Write-Output "没有找到需要执行的sql文件。`r`n"
    }
}
else
{
    Write-Output "没有找到更新脚本目录$($scriptPath)。`r`n"
}

执行效果如下:


猜你喜欢

转载自blog.csdn.net/allenwdj/article/details/72302978
今日推荐