【问题标题】:Using ForEach-Object on Array of Structs - Powershell在结构数组上使用 ForEach-Object - Powershell
【发布时间】:2014-04-01 14:26:19
【问题描述】:

我正在改进我的监视脚本,因此我可以选择一个服务/维护窗口。在两个时间间隔之间忽略所有错误。

这是我得到的:

Add-Type -TypeDefinition @"
public struct ServiceWindow
{
    public int SWStart;
    public int SWEnd;
}
"@

[array]$SWArray = New-Object ServiceWindow
$time = Get-Date -Format HHMM
$time

$ActiveBatchVar = "1000-1005;1306-1345;2300-2305"

$ActiveBatchVar = $ActiveBatchVar.Split(";")

For ($i = 0; $i -lt $ActiveBatchVar.Length; $i++) 
{
    $tempSW = New-Object ServiceWindow
    $tempSW.SWStart = $ActiveBatchVar[$i].Split("-")[0]
    $tempSW.SWEnd = $ActiveBatchVar[$i].Split("-")[1]

    If ($i -eq 0) { $SWArray = $tempSW } else { $SWArray += $tempSW }
}
Write-Host Complete array...
$SWArray

ForEach-Object ($SWArray) {
Get-Date -Format HHMM

If ($time -ge $_.SWStart -and $time -lt $_.SWEnd) {Write-Host Wohoo we have hit a service window service window...}
}  

我在上一个 ForEach-Object 循环中遇到错误。并且无法弄清楚出了什么问题。

关键是我想检查当前时间是否在两个给定时间之间,例如“1000-1005”。

任何人都知道缺少什么,或者可能是简化整个事情的方法;)

【问题讨论】:

  • 您是否打算将 DateTime 格式设置为 HourHourMonthMonth?或者你的意思是说 HHmm?
  • 不,我不是故意的 ;) 感谢您的建议。

标签: arrays powershell struct foreach


【解决方案1】:

好的,这里有几件事...您似乎真的很喜欢 Split() 方法。您可能想研究一些替代方案,例如:

$ActiveBatchVar = @(@("1000","1005"),@("1306","1345"),@("2300","2305"))

看看我们在那里做了什么?它是一个数组数组。 @() 是数组表示法。所以我有一个数组,里面有 3 个数组。

我对结构不是很熟悉,但我对自定义对象很熟悉,所以如果是我,我会使用它。然后你可以这样做:

$SWArray = @() #That's an empty array, we'll add things to it now that it exists
ForEach ($Batch in $ActiveBatchVar){
    $SWArray += New-Object PSObject -Property @{
        SWStart = $Batch[0]
        SWEnd = $Batch[1]
    }
}

然后我们更改最后一位,以便您在下一个循环之前分配 $time 以使其尽可能准确,并稍微更正 ForEach,整个事情看起来像这样:

$ActiveBatchVar = @(@("1000","1005"),@("1306","1345"),@("2300","2305"))

$SWArray = @()
ForEach ($Batch in $ActiveBatchVar){
    $SWArray += New-Object PSObject -Property @{
        SWStart = $Batch[0]
        SWEnd = $Batch[1]
    }
}
Write-Host Complete array...
$SWArray

$time = date -f HHmm
ForEach($SW in $SWArray) {
    If ($time -ge $SW.SWStart -and $time -lt $SW.SWEnd) {
        Write-Host "Wohoo we have hit a service window service window..."
    }
}

【讨论】:

  • 完美,很棒的解释。非常感谢老兄:) “New-Object PSObject -Property”部分有点超出我的理解。但它完全可以正常工作。简单易行。干杯:)
【解决方案2】:

最小改动:

ForEach-Object ($SWArray) {

$SWArray | % {

你最后的Write-Host 也应该将消息括在 quoes 中,即

{Write-Host "Wohoo..."}

【讨论】:

  • 谢谢,感谢您的帮助:)
【解决方案3】:

ForEach-Object ($SWArray) {}

这是错误的语法,你应该使用关键字in

Foreach-Object ($array in $SWArray) {}

【讨论】:

  • 谢谢,感谢您的帮助:)
【解决方案4】:

如果你有一个小数组...

($SWArray).foreach({
Get-Date -Format HHMM
If ($time -ge $_.SWStart -and $time -lt $_.SWEnd) 
 {Write-Host Wohoo we have hit a service window service window...}
})

【讨论】:

  • 谢谢,感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多