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

Using arrays, is there a way to optimize this PowerShell function?

I’m writing a script to mess with call center scammers
Looking for help in optimizing this script to make it as short as possible.
I have the individual messages but when creating the array I have to input each variable manually, is there a way to turn the messages themselves directly into an array so i can loop through them and not have to input them one at a time? I want to be able to add a lot more messages without having to put the variables into the array one at a time.

assistance is appreciated please and thank you

function MsgBox{
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    
    $msg1 = "Are all scammers as dumb as you?"
    $msg2 = "Is the pay worth being this big of a loser?"
    $msg3 = "Do your parents know what you do for a living?"
    
    New-Object -TypeName System.Collections.ArrayList
    $arrlist = [System.Collections.Arraylist]@($msg1, $msg2, $msg3)
    
    Foreach ($item in $arrlist) { 
       [System.Windows.Forms.MessageBox]::Show($item , "Scambait" , 4 , 'Question')
    }
}

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

>Solution :

You can declare an array with all the messages either by comma separated values:

$msgs = 'message 1', 'message 2', 'message 3'

Or by using the array sub-expression operator:

$msgs = @(
    'message 1'
    'message 2'
    'message 3'
)

This would allow you to add new messages to the array easily and the rest of the code would be reduced to a single loop:

foreach($msg in $msgs) {
    # your code using `$msg` here
}
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