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

时间:2016-08-09 04:48:29

标签: windows powershell windows-8.1

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

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

然后我得到:

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
> $test.Substring(3)
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()

我怀疑我必须对以下内容采取措施:

$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

1 个答案:

答案 0 :(得分:0)

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

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

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