【Windows】DevOps PowerShell实现读取ini文件 生成登陆凭证 发送文件到远程服务器 远程服务器执行指令 实现fabric1的基础功能
脚本
function Parse-IniFile {
param(
[string]$Path
)
$ini = @{}
switch -regex -file $Path {
"^\[(.+)\]$" {
$section = $matches[1]
$ini[$section] = @{}
}
"(.+?)=(.+)" {
$name, $value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
function GetCredential {
param (
[string]$Path,
[string]$serverIp
)
# 读取ini
$ini = Parse-IniFile -Path $Path
$user = $ini[$serverIp]["User"]
$password = $ini[$serverIp]["Password"]
#Write-Host $user
#Write-Host $password
# 创建 PSCredential 对象
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $securePassword
return $credential
}
# 将本地文件放到远程服务器上,自动创建对应目录
function Put {
param (
[string]$localFile,
[Object]$credential,
[string]$serverIp,
[string]$remoteFile
)
# 检查本地文件是否存在
if (-not (Test-Path -Path $localFile)) {
Write-Error "Local file does not exist: $localFile"
return
}
# 提取远程文件的目录路径
$remoteDir = Split-Path -Path $remoteFile -Parent
# 创建远程会话
$SessionOption = New-PSSessionOption -SkipCNCheck -SkipCACheck
$session = New-PSSession -ComputerName $serverIp -Credential $credential -Port 5986 -UseSSL -SessionOption $SessionOption -ErrorAction Stop
try {
# 在远程服务器上创建目录(如果不存在)
Invoke-Command -Session $session -ScriptBlock {
param ($dir)
if (-not (Test-Path -Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force
}
} -ArgumentList $remoteDir
# 复制文件到远程服务器
Copy-Item -Path $localFile -Destination $remoteFile -ToSession $session -Force
Write-Output "File copied successfully to $remoteFile on $serverIp"
} catch {
Write-Error "Failed to copy file: $_"
} finally {
# 关闭远程会话
Remove-PSSession -Session $session
}
}
# 在远程执行PowerShell指令
function Run {
param (
[Object]$credential,
[string]$serverIp,
[string]$pscmd
)
# 创建远程会话
$SessionOption = New-PSSessionOption -SkipCNCheck -SkipCACheck
$session = New-PSSession -ComputerName $serverIp -Credential $credential -Port 5986 -UseSSL -SessionOption $SessionOption -ErrorAction Stop
try {
# 在远程服务器上执行命令
$result = Invoke-Command -Session $session -ScriptBlock {
param ($cmd)
Invoke-Expression $cmd
} -ArgumentList $pscmd
# 输出结果
Write-Output $result
} catch {
Write-Error "Failed to run command: $_"
} finally {
# 关闭远程会话
Remove-PSSession -Session $session
}
}
ini文件结构
[server1]
User=user1
Password=password1
[Server2]
User=user2
Password=password2
[Server3]
User=user3
Password=password3
调用示例
调用效果