[Powershell]發佈基於.NET Framework的WebAPI和Job控制檯程序項目

  1. 獲取要發佈的定時計劃任務。
  2. 禁用和停止定時計劃任務。
  3. 批量強制結束Job進程。
  4. 打印定時計劃任務狀態。
  5. 備份項目文件夾。
  6. 發佈項目文件夾。
  7. 刪除部署包。
  8. 啓用定時計劃任務。
<#  
    .NOTES
    ===========================================================================
     Created with:  Visual Studio 2019
     Created on:    2019/8/21 18:17
     Created by:    Allen.Cai
     Organization:  Allen.Cai
     Filename:      deploy_full.ps1
    ===========================================================================
    .DESCRIPTION
        ERP full applications devops scripts.
#>

# 聲明全局變量
# 定義方法開始時輸出的前景色
$LogForegroundColorStart = "Green"
# 定義方法結束時輸出的前景色
$LogForegroundColorEnd = "Cyan"
# 定義方法輸出警告時的前景色
$LogForegroundColorWarning = "DarkYellow"
# 定義發佈目標根路徑
$ProjectRoot = "D:\project"
# 定義備份文件夾根路徑
$BackDirectoryRoot = "D:\backup"
# 定義發佈包根路徑
$DeployDirectoryRoot = "D:\updatasource"
# 定義項目文件夾相對路徑
$ProjectDirectorys = "API1", "API2", "API3", "Job\ALLJob"
# 定義定時計劃任務根路徑
$ScheduledTaskPathRoot = "\Microsoft\ERPJob\"
# 定義定時計劃任務集合
$ScheduledTasks = New-Object System.Collections.ArrayList
# 定義日誌文件路徑
$LogDate = Get-Date
$LogFile = "D:\backup\Deploy_$($LogDate.ToString("yyyyMMddHHmmss")).log"

Start-Transcript -Path $LogFile

# 獲取要發佈的定時計劃任務
Function Get-ScheduledTasks
{
    Write-Host "`nGet the scheduled tasks to be published." -Foreground $LogForegroundColorStart
    Get-ScheduledTask -TaskPath $ScheduledTaskPathRoot | ForEach-Object {
        $taskFullPath = $_.TaskPath + $_.TaskName
        Write-Host $ScheduledTasks.Add($taskFullPath) $taskFullPath
    }
    
    # 屏幕輸出 要執行 禁用、替換、啓用 流程的定時計劃任務
    Write-Host "`nFind $($ScheduledTasks.Count) scheduled tasks :"
    Write-Output $ScheduledTasks
    # 輸出到文件,記錄下待執行的定時計劃任務
    $ScheduledTasks | Out-File "d:\task.list"
    Write-Host "Get the scheduled tasks end." -Foreground $LogForegroundColorEnd
}
Get-ScheduledTasks

# 禁用和停止定時計劃任務
Function Stop-ScheduledTasks
{
    Write-Host "`nDisable and Stop scheduled tasks begin." -Foreground $LogForegroundColorStart
    foreach ($taskFullPath in $ScheduledTasks)
    {
        Write-Host "Disabling and stopping the $taskFullPath scheduled task..."
        # 禁用
        Disable-ScheduledTask "$($taskFullPath)"
        Start-Sleep -m 1000
        
        # 停止
        Stop-ScheduledTask "$($taskFullPath)"
        Start-Sleep -s 3
        Write-Host "Disabled and stopped the $taskFullPath scheduled task."
    }
    Write-Host "Disable and Stop scheduled tasks end." -Foreground $LogForegroundColorEnd
}
Stop-ScheduledTasks

# 批量強制殺掉Job進程,避免上面的Stop-ScheduledTask命令沒結束Job進程
Function Kill-Job
{
    try
    {
        Write-Host "`nBatch force killing of the Job process." -Foreground $LogForegroundColorStart
        # 屏幕輸出Job進程狀態信息, 如果沒有正在運行的Job進程,會停止執行後面命令並且拋出異常
        Get-Process -Name Job -ErrorAction Stop
        # 強制終止Job進程, 如果沒有正在運行的Job進程,會停止執行後面命令並且拋出異常
        Stop-Process -Name Job -Force -ErrorAction Stop
        Start-Sleep -s 5
        Write-Host "Batch force killing of the Job process successed." -Foreground $LogForegroundColorEnd
    }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]
    {
        Write-Host "The Job process that needs to be forced to kill was not found." -Foreground $LogForegroundColorWarning
    }
}
Kill-Job

# 屏幕輸出定時計劃任務狀態,看是否已全部禁用和停止
Function Print-ScheduledTasks
{
    Write-Host "`nPrinting the status of scheduled tasks." -Foreground $LogForegroundColorStart
    # 逐個輸出任務狀態
    #   foreach ($taskFullPath in $ScheduledTasks)
    #   {
    #       $lastIndex = $taskFullPath.LastIndexOf("\") + 1;
    #       $taskPath = $taskFullPath.SubString(0, $lastIndex)
    #       $taskName = $taskFullPath.SubString($lastIndex)
    #       
    #       Get-ScheduledTask -TaskPath "$($taskPath)" -TaskName "$($taskName)"
    #   }
    # 一次性輸出所有任務狀態
    Get-ScheduledTask -TaskPath $ScheduledTaskPathRoot
    Write-Host "Print the status of scheduled tasks end." -Foreground $LogForegroundColorEnd
}
Print-ScheduledTasks

# 備份項目文件夾
Function Backup-Directory
{
    Write-Host "`nBackuping project folders." -Foreground $LogForegroundColorStart
    
    # 定義備份文件夾所需要的參數
    $CurrentDate = Get-Date
    $BackupTime = $CurrentDate.ToString("yyyyMMddHHmmss")
    $DisplayTime = $CurrentDate.ToString("yyyy-MM-dd HH:mm:ss")
    $BackDirectoryCurrent = $BackDirectoryRoot + "\" + $BackupTime
    
    foreach ($item in $ProjectDirectorys)
    {
        Write-Host "Backup the $item project..."
        # 創建備份文件夾
        New-Item -ItemType "directory" -Path "$BackDirectoryCurrent\$item" -ErrorAction SilentlyContinue
        # 拷貝項目文件夾到備份文件夾
        Copy-Item "$ProjectRoot\$item\*" -Destination "$BackDirectoryCurrent\$item\" -Recurse -Force
        Write-Host "Backup $item project successfully."
    }
    
    Write-Host "$DisplayTime $ProjectRoot backup successful. details:"
    
    # 屏幕輸出備份文件夾的目錄路徑和大小
    $BackDirectoryChildItems = Get-ChildItem $BackDirectoryCurrent | Where-Object { $_.PsIsContainer -eq $true }
    $BackDirectoryChildItems | ForEach-Object {
        $item = $_
        $subFolderItems = (Get-ChildItem $item.FullName -Recurse | Where-Object { -not $_.PSIsContainer } | Measure-Object -property length -sum)
        $item.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + "MB"
    }
    
    Write-Host "Backup project folders end." -Foreground $LogForegroundColorEnd
}
Backup-Directory

# 發佈項目文件夾
Function Deploy-Projects
{
    Write-Host "`nThe $($ProjectDirectorys.Length) projects are being deployed." -Foreground $LogForegroundColorStart
    foreach ($item in $ProjectDirectorys)
    {
        Write-Host "Deploying the $item project..."
        # 先假設目標路徑不存在,嘗試創建新目錄,如果存在,則跳過
        New-Item -ItemType "directory" -Path "$ProjectRoot\$item\" -ErrorAction SilentlyContinue
        $projectParentPath = Split-Path -Parent "$ProjectRoot\$item"
        Copy-Item "$DeployDirectoryRoot\$item" -Destination $projectParentPath -Recurse -Force
        Write-Host "Deployed $item project successfully."
    }
    Write-Host "The $($ProjectDirectorys.Length) projects were successfully deployed." -Foreground $LogForegroundColorEnd
}
Deploy-Projects

# 刪除部署包
Function Remove-DeployPackages
{
    Write-Host "`n$($ProjectDirectorys.Length) packages are being removed." -Foreground $LogForegroundColorStart
    foreach ($item in $ProjectDirectorys)
    {
        Write-Host "Removing the $item package..."
        Remove-Item -Path "$DeployDirectoryRoot\$item" -Recurse -Force -ErrorAction SilentlyContinue
        Write-Host "Removed $item package successfully."
    }
    Write-Host "$($ProjectDirectorys.Length) packages were successfully removed." -Foreground $LogForegroundColorEnd
}
Remove-DeployPackages

# 啓用定時計劃任務
Function Enable-ScheduledTasks
{
    Write-Host "`nEnable scheduled tasks begin." -Foreground $LogForegroundColorStart
    foreach ($taskFullPath in $ScheduledTasks)
    {
        Enable-ScheduledTask "$($taskFullPath)"
    }
    Write-Host "Enable scheduled tasks end." -Foreground $LogForegroundColorEnd
}
Enable-ScheduledTasks

# 再次屏幕輸出定時計劃任務狀態
Print-ScheduledTasks

Stop-Transcript
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章