mardi 9 mai 2017

Powershell- If-else inside a foreach doesn't return what I think it should

I have an array of servers that I need to loop through, and have an attribute assigned only to specific servers (this happens later in the script).

I'm likely missing something obvious (I'm new-ish to PS), and I've been struggling with this most of the day.

Here's the array:

$test =@('test_dc','test_fp','test_ts','test_ap')

In the array, I have a domain controller, file/print, terminal server, and application servers (in that order).

The only servers that should get the attribute are the fp, ts, and ap servers.

Here's what I've tried thus far:

foreach ($item in $test) {
  write-host $item "`n"
  write-Host "Start IF here `n"
  if ($item.name -like '*fp*'){ 
    write-Host "Found $item"
  } else {
    write-Host "ELSE `n"
    write-host '-=-=-=-=-'
  }
 }

Here's the output from that:

PS C:\Users\me\Desktop> .\scratch.ps1

test_dc

Start IF here

ELSE

-=-=-=-=-

test_fp

Start IF here

ELSE

-=-=-=-=-

test_ts

Start IF here

ELSE

-=-=-=-=-

test_ap

Start IF here

ELSE

-=-=-=-=- PS C:\Users\me\Desktop>

According to the way I think it should work, I should see this:

test_fp

Found test_fp

I've also tried this:

if ($test -contains '*fp') {
  Write-Host "Found $_"
  } else {
    write-host 'end'
  }

and I just get an empty line.

Thank you for any help!

Joe

Aucun commentaire:

Enregistrer un commentaire