Pass array to function? (only add if not a duplicate)

hello, I’m still new to PS but I’m currently stuck trying to automate some annoying tasks.

I have this function that doesn’t really behave like I’d expect it to:

function CheckForDupes($entryName, $inputArray) {
	
	$isNewBool = !($entryName -in $inputArray)

	if($isNewBool){$inputArray += $entryName}
	Write-Host $inputArray
	
	return $isNewBool
}

in main I’m calling CheckForDupes like this

$dupeArray = @('one', 'two', 'check')

for ($i = 2; $i -le $lastRow; $i++) {
  Write-Host $dupeArray
  if (CheckForDupes($newstring, $dupeArray)) {
    #my code
  }
}

now the strange thing is that $dupeArray doesn’t seem to be used by my CfD function. Write-Host inside CfD just writes the element that was just now added, while the Write-Host outside the function remains “one two check”

Any help would be appreciated!

Felix,
Welcome to the forum. :wave:t3:

What is $lastRow? You did not define this variable in the code you shared.

That’s not how we call functions in PowerShell. The proper way is this:

  if (CheckForDupes -entryName $newstring -inputArray $dupeArray) {

Since you return more than just a $true or $false from your function because of the Write-Host in your function what do you expect to happen when you use your function inside an if statement?

In general I’d recommend to change your function slightly. If the name says “Check” for dupes I think it should not do more than that. :wink:

Thanks for the quick reply

lastRow is just how many rows are filled in the excel sheet I’m reading, just wanted to illustrate that we’re inside a loop

the Write-Host bits I just used for debugging they’re not supposed to be in there. That’s how I realized that it’s just creating a new array everytime it’s called instead of checking and adding to the one I put in the parameter.

What I’d expect to happen is the function being called, checking if the string is already contained in $dupeArray, if it’s not, then add it and return true, if it is return false

OK, did you change the function call and tried it? :man_shrugging:

That’s a kind of very bad design thow. You function should return either a true or false OR an updated or untouched array - not both!!! That’s what I meant. If you name your function “Check” it should only check and return the result true or false. If you want to update your array or add an ellement to it you should name your function Add or Update. You could still check if the element is already there and return an error in such a case. :point_up:

If this is just for debugging you should use Write-Debug instead. This way it does not pollute your default return stream / pipeline and you can turn it on and off with a switch parameter. :man_shrugging: