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

Substring() fails - need to cast result as string instead of default double

在尝试之前,我认为子字符串很容易:

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

然后我得到:

1
2
3
4
5
6
Method invocation failed because [System.Double] does not contain a method named 'Substring'.
At line:1 char:1
+ $test.Substring(0,2)
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
1
> $test.Substring(3)
1
2
3
4
5
6
Method invocation failed because [System.Double] does not contain a method named 'Substring'.
At line:1 char:1
+ $test.Substring(3)
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

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

我怀疑我必须对以下内容做一些事情:

1
2
3
4
5
6
$page | Select-String -Pattern $mmddyyyyRgx -AllMatches |
    % { $_.Matches } |
    % { $_.Value } |
    Select-String -Pattern $mmddRgx -AllMatches |
    % { $_.Matches } |
    % { $_.Value } -Outvariable mmdd

因为$ mmdd给了我:

1
0.888888888888889

这是双重信号,无法像下面那样进行投射:

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

它将给我
0。
代替
08


只需在$mmdd上调用ToString()方法,即可使用SubString()

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

但是,也许您告诉我们您的实际问题,因为这可能是XY问题。