使用PowerShell脚本更新数据库
2017-05-16 16:19
513 查看
在很多时候,我们在发布程序的时候,都需要更新数据库,以前我的做法是,手动去执行更新脚本,但是后来思考,我们是不是可以做的更加自动化点,于是就考虑用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"
}
执行效果如下:
脚本如下:
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"
}
执行效果如下:
相关文章推荐
- 数据库管理——Powershell——使用Powershell脚本找出消耗最多磁盘空间的文件
- shell使用sql脚本进行sqlite3数据库更新
- 数据库管理——Powershell——使用Powershell脚本找出消耗最多磁盘空间的文件
- 使用powershell脚本批量更新客户端配置文件
- 如何使用Powershell脚本监控Exchange2010(一) 数据库Mount状态的监控
- 使用PowerShell脚本来轮训Exchange数据库的状态
- [11月26日的脚本] 使用PowerShell列举数据库中未被使用的内容数据库
- 如何使用Powershell脚本监控Exchange2010(一) 数据库Mount状态的监控
- 数据库管理——Powershell——使用Powershell脚本找出消耗最多磁盘空间的文件
- ADO.NET中使用getchanges方法提速(更新回数据库操作)
- DataAdapter数据集DataSet和数据库的同步(3):使用CommandBuilder来更新数据集
- 使用游标批量更新/填充数据库(The Using of Cursor)
- 更新、插入数据库所使用的UPDATE()
- 使用病毒数据库离线更新包
- 使用 DataAdapter 和 DataSet 更新数据库
- 使用 DataAdapter 和 DataSet 更新数据库 [C#]
- 使用 Visual C# .NET 从数据集对象更新数据库
- 使用 DataAdapter 和 DataSet 更新数据库 [C#]
- 使用 DataAdapter 和 DataSet 更新数据库
- NBear - 使用Entity Configurator设置实体元数据、生成数据库创建脚本