我试图组合这个Powershell命令输出的每两行:
(((Invoke-WebRequest -Uri "https://www.timeanddate.com/holidays/us/$(Get-Date -Format yyyy)").Content | sls 'id=holidays') -split '<th class="nw" >' | Out-String -Stream) -replace '<|>',',' | ForEach-Object {$_.Split(',')[10,0];}如您所见,如果您运行它,它将输出当前年度的假期及其日期,如下所示:
New Year's Day
Jan 1
World Braille Day
Jan 4
Epiphany
Jan 6
Orthodox Christmas Day
Jan 7
International Programmers' Day
Jan 7
etc.我的目标是输出如下:
New Year's Day Jan 1
World Braille Day Jan 4
Epiphany Jan 6
Orthodox Christmas Day Jan 7
International Programmers' Day Jan 7
etc.任何建议都是受欢迎的(我希望在此过程中不将输出写入文件)。或者,如果有一个更有效的方法,我也对此持开放态度。
发布于 2020-08-21 18:43:22
使用一个简单的for循环,其计数器每次递增2次:
$splitLines = (((Invoke-WebRequest -Uri "https://www.timeanddate.com/holidays/us/$(Get-Date -Format yyyy)").Content | sls 'id=holidays') -split '<th class="nw" >' | Out-String -Stream) -replace '<|>',',' | ForEach-Object {$_.Split(',')[10,0];}
for($i = 0; $i -lt $splitLines.Count; $i += 2){
$splitLines[$i,($i+1)] -join ' '
}发布于 2020-08-21 18:45:16
你可以沿着这条路线做点什么。由于某些原因,我必须在这里使用模数4,而不是2,因为当我像这样分裂时,它使第二行空。
$inputData = @"
New Year's Day
Jan 1
World Braille Day
Jan 4
Epiphany
Jan 6
Orthodox Christmas Day
Jan 7
International Programmers' Day
Jan 7
"@
$splitData = $inputData.Split([Environment]::NewLine)
# use a dot here to make the output availabe after the iteration is completed
$splitData | . {
begin {
$output = ""
$i = 0
}
process {
if(0 -eq $i % 4) {
$output += $_ + [Environment]::NewLine
}
$i = $i + 1
}
}
Write-Output $output
# New Year's Day
# World Braille Day
# Epiphany
# Orthodox Christmas Day
# International Programmers' Day它不是完美的,但它适用于给定的问题,我建议对它进行修补,使它更好。有一段时间没有使用PowerShell了。
https://stackoverflow.com/questions/63528026
复制相似问题