Home > OS >  Powershell - Verify If a indexof is empty
Powershell - Verify If a indexof is empty

Time:12-11

if (($signmail.IndexOf('@')) -ne $null)
   {
   $signname = $signmail.Remove($signmail.IndexOf('@'))
   }
Else{
   $signname = $signmail
   }

Hi, basicaly, I try to see if the user enter his mail address completely, or just the first part. I try here to ask If the value after a @ in the mail address is not empty, to erase it and put it in the new variable. If not, the variable give directly his name to the other variable. But it not work. I always receive the StartIndex can't be below 0 error.

Anyone think of a way to make this code work for that part ?

Thanks

CodePudding user response:

From the String.IndexOf() documentation:

Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

So you'll want to test whether the return value is 0 or greater:

if ($signmail.IndexOf('@') -ge 0) {
    $signname = $signmail.Remove($signmail.IndexOf('@'))
}
else {
    $signname = $signmail
}
  • Related