powershell - 将 Powershell 脚本转换为 jenkins 作业
问题描述
我有以下功能:
function DivideAndCreateFiles ([string] $file, [string] $ruleName) {
$Suffix = 0
$FullData = Get-Content $file
$MaxIP = 40
while ($FullData.count -gt 0 ){
$NewData = $FullData | Select-Object -First $MaxIP
$FullData = $FullData | Select-Object -Skip $MaxIP
$NewName = "$ruleName$Suffix"
New-Variable -name $NewName -Value $NewData
Get-Variable -name $NewName -ValueOnly | out-file "$NewName.txt"
$Suffix++
}
}
这个函数需要一个文件位置,这个文件包含数百个 ip。然后它迭代文件并从中创建文件,每个文件都包含 40 个 IP,将其命名为 $rulename$suffix 所以如果 $rulename=blabla
我会得到 blabla_0、blabla_1 等等,每个都有 40 个 ips。
我需要转换此逻辑并将其放入 jenkins 作业中。该文件位于作业的工作目录中,名为 ips.txt
suffix = 0
maxIP = 40
ips = readFile('ips.txt')
...
解决方案
您可以使用以下 groovy 代码轻松实现此目的:
def divideAndCreateFiles(path, rule_name, init_suffix = 0, max_ip = 40){
// read the file and split lines by new line separator
def ips = readFile(path).split("\n").trim()
// divide the IPs into groups according to the maximum ip range
def ip_groups = ips.collate(ips.size().intdiv(max_ip))
// Iterate over all groups and write them to the corresponding file
ip_groups.eachWithIndex { group, index ->
writeFile file : "${rule_name}${init_suffix + index}", text: group.join("\n")
}
}
从我的角度来看,因为您已经在 groovy 中编写了完整的管道,所以在 groovy 中处理所有逻辑会更容易,包括这个函数。
推荐阅读
- java - Java游戏:根据玩家的位置限制棋盘的可见性
- javascript - 在 VRView for web 中禁用陀螺仪/设备方向读取
- javascript - 节点奇怪的用户输入异步行为
- reactjs - Memoize 和 lodash 时间获取索引,创建唯一的文本输入
- linux - 如何通过 api 在容器内执行命令
- python - 将 Flask 链接到 PostgresQL
- c# - Unity:《小翅膀》类游戏的 AI 建议
- php - 3张表之间的Laravel关系
- javascript - jQuery 多个加/减计数器
- c# - 我的代码需要 SELECT 而我只使用 INSERTS