Jenkins通過Publish Over SSH插件遠程部署war包到windows操作系統的tomcat上使用的Powershell腳本

E:
cd E:\app\tomcat\

# 預先設定要操作的文件地址、端口變量
$sourceFile = "E:\app\tomcat\update\myProject.war"
$targetFile = "E:\app\tomcat\webapps\ROOT.war"
$dateTime = Get-Date -Format 'yyyyMMddHHmmss'
$renameFile = "E:\app\tomcat\update\myProject_$dateTime.war"
$port = ":8080"

# 先判斷要發佈的文件是否存在
if (test-path $sourceFile) {
    Copy-Item $sourceFile $targetFile
    Write-Host $sourceFile' has success copy to '$targetFile
} else {
    Write-Host $sourceFile 'Files is not Exist!'
    exit
}

# 按端口找到tomcat(java)進程ID(pid)
$str = netstat -ano|findstr $port
$list = $str.Split('\n'); 
for ($i=0;$i -lt $list.Length; $i++) {
    $item_list = [System.Text.RegularExpressions.Regex]::Split($list.Get($i).Trim(), '\s+')
    for ($j=0;$j -lt $item_list.length; $j++) {
        if ($list.Get($i).contains($port)) {
            $p_id = $item_list.Get(4)
            Write-Host '$p_id'+$p_id
            break;
        }
    }
}

if($p_id -eq $null) {
    Write-Output $port 'port is free'
} else {
    Write-Output $port 'port is be used:'
    Get-Process -id $p_id
    Stop-Process -id $p_id
    Write-Host 'kill '$port' process success'
}

#清空webapps目錄和work目錄
Function emptyDir($TargetFolder) {
    $Files = get-childitem $TargetFolder -force
    Foreach ($File in $Files) {
	    $FilePath=$File.FullName
	    Remove-Item -Path $FilePath -Recurse -Force
    }
    return 1;
}
$isEmpty1 = emptyDir webapps
$isEmpty2 = emptyDir work

# 移動部署war到部署目錄
if($isEmpty1 -eq "1" -and $isEmpty2 -eq "1") {
    Copy-Item $sourceFile $targetFile
    Write-Host $sourceFile' has success copy to '$targetFile
}
sleep -Seconds 5

# 啓動tomcat
.\bin\startup.bat
sleep -Seconds 5

# 後續操作:修改暫存目錄中的發佈包名稱
rename-Item $sourceFile -NewName $renameFile
Write-Host $sourceFile ' has success renamed '$renameFile
exit

注:該腳本在win10操作系統powershell5.1環境下測試可用
在這裏插入圖片描述

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