Home > Enterprise >  Increase Substring length dynamically
Increase Substring length dynamically

Time:08-16

I am new to the community and need some help in Powershell.

I want the following code to dynamically check if the specific $sAMAccountName exists in an array or not. If it exists, keep increasing the substring length by 1 and check the array again. Instead of defining more variables like $sAMAccountName1 and $sAMaccountName2 (and so on) manualy.

$Nachname = "Nachname"
$Vorname = "Vorname"
$sAMAccountName = $Nachname $Vorname.Substring(0,1)
$sAMAccountName1 = $Nachname $Vorname.Substring(0,2)
$sAMAccountName2 = $Nachname $Vorname.Substring(0,3)
$Array = @('NachnameV','NachnameVo','NachnameVor')


if($sAMAccountName -notin $Array){
    Write-Host "$sAMAccountname does not exist :-)"
}
elseif($sAMAccountName1 -notin $Array){
    Write-Host "$sAMAccountName1 does not exist :-)"
}
elseif($sAMAccountName2 -notin $Array){
    Write-Host "$sAMAccountName2 does not exist :-)"
}
else{
    Write-Host "$sAMAccountName2 does exist :-("
}

Thank you for your help.

Greetings, PalimPalim

CodePudding user response:

This may do what you need :

$Nachname = "Nachname"
$Vorname = "Vorname"
#$sAMAccountName = $Nachname $Vorname
$Array = @('NachnameV','NachnameVo','NachnameVor')

$i = 0
do {
    $i  
    $sAMAccountName = $Nachname $Vorname.Substring(0,$i)
    write-host "i = $i"
    write-host "account name = $sAMAccountName"
    if($sAMAccountName -in $Array){
    Write-Host "$sAMAccountName found"
    }

} until ($sAMAccountName -notin $array)

Write-Host "$($Nachname $Vorname.Substring(0,$i)) not found"

Where $i is used as an index which increases by 1 within the do until loop until the name being searched for no longer shows up in the array.

The write-host lines for i=$i and the account name aren't needed, but just let you see what the script is doing on each iteration round the loop, and can be removed.

  • Related