Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increase Substring length dynamically

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Greetings,
PalimPalim

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading