Link to home
Get AccessLog in
Avatar of yo_bee
yo_beeFlag for United States of America

asked on

Trouble getting Powershell IF THEN to work

I have a question about IF THEN in powershell.
I have a text file that contains First names  
I have an array with $Folder.fullname or $Folder.name
I want to ignore all items that match Firstname
$firstname = Get-Content -Path 'C:\temp\file.txt'
$Folders = Get-Childitem -path '\\Server1\Folders' -Direcotry

Foreach ($folder in $folders)
{
If ($folder.name -match $firstname) 
           {
                 <Do Something>
           }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Avatar of yo_bee

ASKER

It returns all ?

Note:
The text file content looks like this:

Sub1
Sub2
Sub3
Sub4
Avatar of yo_bee

ASKER

IF worked
Avatar of oBdA
oBdA

Can't reproduce.
Test setup:
PS C:\> Get-Childitem -path 'C:\Folders' -Directory | Select Name

Name
----
Sub0
Sub1
Sub2
Sub3
Sub4
Sub5


PS C:\> Get-Content -Path 'C:\Folders\file.txt'
Sub1
Sub2
Sub3
Sub4

Open in new window

Script 1:
PS C:\> Get-Content -Path 'C:\Folders\file.txt'
Sub1
Sub2
Sub3
Sub4
PS C:\> $firstnames = Get-Content -Path 'C:\Folders\file.txt'
PS C:\> Get-Childitem -path 'C:\Folders' -Directory |
>> Where-Object {$firstnames -contains $_.Name} |
>> ForEach-Object {
>>  "$($_.Name): Do something"
>> }
>>
Sub1: Do something
Sub2: Do something
Sub3: Do something
Sub4: Do something

Open in new window

Script 2:
PS C:\> $firstnames = Get-Content -Path 'C:\Folders\file.txt'
PS C:\> Get-Childitem -path 'C:\Folders' -Directory | ForEach-Object {
>> If ($firstnames -contains $_.Name) {
>>  "$($_.Name): Do something"
>> } Else {
>>  "$($_.Name): Do something else"
>> }
>> }
>>
Sub0: Do something else
Sub1: Do something
Sub2: Do something
Sub3: Do something
Sub4: Do something
Sub5: Do something else

Open in new window