1
votes

I thought substring is easy until I tried:

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

Then I get:

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

How do I cast the variable $mmdd to string so I can use Substring() on it?

I suspect I have to do something to the following:

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

Since $mmdd gave me:

0.888888888888889

it's a double balue, casting like below will not work as expected:

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

it will give me 0. instead of 08

1
Does "Write-Host $mmdd" really return "08/09"? Since it says that it's a double that shouldn't be the case. $mmdd.ToString().Substring(0,2) should work either way. When you store the value into $mmdd it should also work to declare it as a string [string]$mmdd = x.Erik Blomgren
no. returns something like 0.888888...9. it treats 08/09 as division result! I got around that by extracting with regex more than just "08/09" and ended up with a collection; on which I use [0] index and .Substring to get what I want. quite a few juggles to get the result.gg89

1 Answers

1
votes

Just call the ToString() method on $mmdd so you can use SubString():

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

However, maybe you tell us about your actual problem since this could be a XY Problem.