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

Time:04-09

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')
    }
}

CodePudding user response:

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
}
  • Related