-1

I have this script: Can I add a loop ; after I Enter ID & IP and add in 'db.csv' go back to ask again $inputID and a loop for ask if typed ID or IP is good (?)

I need 2 'loops' in this script first loop for the confirmation typed if info is good or not >> if not go back to add again ;; and second loop after I add ID, IP and script write in csv new ID go again in top of script where need to $inputID for type newest ID which added previous.

#### START SCRIPT #####

Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
 
$dbfile = "C:\test.csv"

$db = [System.Collections.Generic.List[object]]::new()
if (Test-Path -Path $dbfile -PathType Leaf) { $db.AddRange((Import-Csv -Path $dbfile)) }
$dbUpdated = $false 

while ($true) {
    While ( ($Null -eq $inputID) -or ($inputID -eq '') ) {
    $inputID = Read-Host -Prompt "Introduceti ID sau Tastati 'Q' for exit"  
} 
    if ($inputID -eq 'q') { break }

    $entry = $db | Where-Object { $_.HostName -eq $inputID }
    if ($entry) {
        Write-Host "$inputID Ok!" -ForegroundColor Green
        continue
    }

    Write-Host "$inputID nu exista in baza de date!" -ForegroundColor Red
    # ask for confirmation
    $title    = 'Adaugare ID nou?'
    $question = 'Doriti sa introduceti un ID nou in Baza de Date?'
    $choices  = '&Yes', '&No'
    $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
    if ($decision -ne 0) {
        continue
    }

    do {
        $IP = Read-Host -Prompt "Introduceti IP pentru: $inputID"
    } while (![IPAddress]::TryParse($IP, [ref]$null))

    $db.Add([PsCustomObject]@{ HostName = $inputID; IP = $IP })
    Write-Host "Data : $inputID,$IP adaugat cu succes in baza de date!"
    $dbUpdated = $true
}

if ($dbUpdated) {
    $db | Export-Csv -Path $dbfile -NoTypeInformation -Force

    $dbTrimmer = Get-Content $dbfile
    $dbTrimmer.Replace('","', ",").TrimStart('"').TrimEnd('"') | Set-Content -Path $dbfile -Force -Confirm:$false 
}

# Script continue. If put correct ID run the script below if not Ask if want to add new ID after that return to ask ID (of course here I typed new ID which I enter before in db) and run the script for that ID.
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    There's not really enough information in your question - can you describe what you're trying to achieve, and what doesn't work in your current script. See https://stackoverflow.com/help/how-to-ask for more help with posting "good" questions. – mclayton Oct 29 '21 at 11:14
  • hello mclayton I update my post. Thank you –  Oct 29 '21 at 11:33

1 Answers1

0

I would do this inside one endless while {..} loop where another do{..} while() is used for the second question about the IP.

Also, you can do all from memory and only write the data to file after the user quits the while loop (and only if an update was made)

Something like this:

$dbfile =  "C:\test.csv"

# create a List object to store and update the data in memory
$db = [System.Collections.Generic.List[object]]::new()

# if the file can be found, import the data and add to the $db List 
if (Test-Path -Path $dbfile -PathType Leaf) { $db.AddRange((Import-Csv -Path $dbfile)) }

# create a flag to check later if an new entry was made
$dbUpdated = $false  

# enter an endless loop
while ($true) {
    $inputID = Read-Host -Prompt "Introduceti ID. Type 'Q' to exit"
    # break the loop if the user wants to stop
    if ($inputID -eq 'q') { break }  

    # test if the id is already in the $db collection
    $entry = $db | Where-Object { $_.HostName -eq $inputID }
    if ($entry) {
        Write-Host "$inputID Ok!" -ForegroundColor Green
        continue  # go back to asking for a new ID
    }

    Write-Host "$inputID nu exista in baza de date!" -ForegroundColor Red
    # ask for confirmation
    $title    = 'Add New ID?'
    $question = 'Doriti sa introduceti un ID nou in Baza de Date?'
    $choices  = '&Yes', '&No'
    $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
    if ($decision -ne 0) {
        continue  # go back to asking for a new ID
    }

    # ask for IP for this new entry
    do {
        $IP = Read-Host -Prompt "Introduceti IP for $inputID"
    } while ([string]::IsNullOrWhiteSpace($IP))
    # you may want to change the 'while' condition above to 
    #   while (![IPAddress]::TryParse($IP, [ref]$null))
    # to ensure a valid IP address is entered.

    # add the given ID and IP to the $db collection in memory
    $db.Add([PsCustomObject]@{ HostName = $inputID; IP = $IP })
    Write-Host "Data : $inputID,$IP adaugat cu succes in baza de date!"
    $dbUpdated = $true
}

# here we can test if new entries have been added
if ($dbUpdated) {
    # overwrite the file with the updated info
    $db | Export-Csv -Path $dbfile -NoTypeInformation -Force

    # Apparently you don't want quotes in the CSV file, and in this case it would be safe enough to do
    $dbTrimmer = Get-Content $dbfile
    $dbTrimmer.Replace('","', ",").TrimStart('"').TrimEnd('"') | Set-Content -Path $dbfile -Force -Confirm:$false

    # but please be VERY careful with that because in other csv files, the fields may contain
    # Newlines, the delimiter character itself or quotes and if that is the case, the csv file 
    # will become unusable.. 
    # See https://stackoverflow.com/a/69705776/9898643 to do that safely. 
}
Theo
  • 57,719
  • 8
  • 24
  • 41
  • Hello Theo , Thank you soo much for your help. Works very well but here is only one problem. If I type 'corect ID and this id is in db.csv' jump over the "add new id?" and run the following script. I edit my first post with your code. Thanks a lot again. –  Oct 31 '21 at 09:38
  • @Bogdan If you want it to perform some action when you enter an existing ID, then I would suggest putting that action inside the `if ($entry) {..}` condition, just above the `continue` statement. Then when that action is done, the loop will take you back to where it asks for an ID or exit by pressing `Q`. – Theo Oct 31 '21 at 11:00
  • Hello Theo, I try this , all works well but after I put ID correct > Return > ID is correct > Running script on this ID - OK after script running in loop for this ID.. over and over. –  Oct 31 '21 at 14:37
  • 1
    @Bogdan Yes, because that is what you asked for in your original question _"Enter ID & IP and add in 'db.csv' **go back to ask again $inputID**"_. The line `$inputID = Read-Host -Prompt "Introduceti ID. Type 'Q' to exit"` lets the user quit if he wants to, OR carry on with the script and enter a new ID. Where else would you like to exit the loop?? If you want the script to stop there, replace `continue` with `break` – Theo Oct 31 '21 at 14:44
  • 1
    I replace all 'continue' with break and now seems to works how I want ; thank youu!! –  Oct 31 '21 at 15:03