Substring()失败-需要将结果强制转换为字符串而不是默认的double类型



我认为子字符串很容易,直到我尝试:

# extract from a webpage with regex into $mmdd the value like 08/09
Write-Host $mmdd
08/09
$mmdd.Substring(0,2)

得到:

方法调用失败,因为[System.]Double]不包含名为"Substring"的方法。在line:1 char:1+ $ test.Substring (0, 2)+ ~~~~~~~~~~~~~~~~~~~~+ CategoryInfo: InvalidOperation:(:) [], RuntimeException+ fulllyqualifiederrid: MethodNotFound
> $test.Substring(3)
方法调用失败,因为[System.]Double]不包含名为"Substring"的方法。在line:1 char:1+ $ test.Substring (3)+ ~~~~~~~~~~~~~~~~~~+ CategoryInfo: InvalidOperation:(:) [], RuntimeException+ fulllyqualifiederrid: MethodNotFound

我如何将变量$mmdd转换为字符串,以便我可以使用Substring() ?

我怀疑我必须对以下内容做些什么:

$page | Select-String -Pattern $mmddyyyyRgx -AllMatches |
    % { $_.Matches } |
    % { $_.Value } |
    Select-String -Pattern $mmddRgx -AllMatches |
    % { $_.Matches } |
    % { $_.Value } -Outvariable mmdd

自从$mmdd给了我:

0.888888888888889

它是一个双值,像下面这样的强制转换不会像预期的那样工作:

[string]$mmdd.Substring(0,2)

它会给我0.而不是08年

$mmdd上调用ToString()方法,这样就可以使用SubString():

$mmdd.ToString().SubString(0,2)

然而,也许你告诉我们你的实际问题,因为这可能是一个XY问题。

最新更新