powershell - StartsWith 在开关中

标签 powershell powershell-2.0

我正在尝试解析一些 Autodesk Revit 日志文件,这些文件的注释行均以撇号开头,而命令行则没有。注释行可以进一步以 'E 或 'H 或 'C 开头,以表示我也需要使用的时间戳。所以我想我的逻辑是:

If Comment
  Switch TimeStampType
Else
  Command

我找到了 this ,我想如果 switch ($someString.ToLower()) 有效,那么 switch ($line.StartsWith()) 也会有效(我知道,这有点达到,因为 ToLower 和 StartsWith 是完全不同的概念)。

然而,这是 throw 找不到“StartsWith”的重载和参数计数:“0”。if ($line.StartsWith("'")) 处。但这有点误导,因为如果我 REM 整个开关它不会抛出任何错误,所以错误一定在开关中。

        if ($line.StartsWith("'")) {
            switch ($line.StartsWith()) {
                "'E " {
                    # handle Timestamp
                }
                "'H " {
                    # handle Timestamp
                }
                "'C " {
                    # handle Timestamp
                }
                Default {}
            }
        } else {
            if ($line -like "*$command*") {
                Write-Host "$line"
            }
        }

我也尝试过使用 ` 转义撇号,结果相同,并按照链接中的建议使用这样的开关。

{$_ -eq "'E "} {
        # handle Timestamp
}

同样的结果。所以最后我得到了

    if ($line.StartsWith("'")) {
        switch ($line) {
            $_.StartsWith("'E ") {
                # handle Timestamp
            }
            $_.StartsWith("'H ") {
                # handle Timestamp
            }
            $_.StartsWith("'C ") {
                # handle Timestamp
            }
            Default {}
        }
    } else {
        if ($line -like "*$command*") {
            Write-Host "$line"
        }
    }

这行得通,但也似乎不够优雅。那么,我是否找到了一个或最佳答案,或者这里是否有我所缺少的更好的方法?

最佳答案

而不是使用 String.StartsWith() , 你可以只使用 wildcard switch :

switch -wildcard ($line){
  "'E *" {
    # $line starts with 'E
  }
  "'H *" {
    # $line starts with 'H
  }
  "'C *" {
    # $line starts with 'C
  }
}

或正则表达式开关:

switch -regex ($line){
  "^'E " {
    # $line starts with 'E
  }
  "^'H " {
    # $line starts with 'H
  }
  "^'C " {
    # $line starts with 'C
  }
}

请注意,如果您使用 "somestring".StartsWith() 作为您的开关输入参数,您将捕获的唯一值将是 $true$false,因为这是 StartsWith() 返回的内容:

switch($line.StartsWith("'E")){
  $true {
    # $line starts with 'E
  }
  $false {
    # $line doesn't start with 'E 
  }
}

关于powershell - StartsWith 在开关中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41417287/

相关文章:

powershell - 如何获取Get-ADComputer的默认集中的Description属性?

powershell - Splatting 哈希表 - Start-Process -ArgumentList

powershell - 无法找到类型 [System.IO. Compression. CompressionLevel] : make sure that the assembly containing this type is loaded

powershell-2.0 - ForEach-Object 中出现意外标记 "in"

powershell - WMI筛选器出现问题

windows - Powershell脚本协助请

string - 将cmdlet设置为变量而无需立即调用它

powershell - 从批处理重定向到Powershell

powershell - 获取由 Invoke-WmiMethod 启动的进程的状态

Powershell - 如何使用多项选择调用复选框窗口