"ForEach" looping, help with syntax

I am only 2 days into PowerShell after watching Jeff Hicks’s 3-part PowerShell Essentials videos, so I apologize for the newbie obvious mistakes (20+ years programming, none in PowerShell !!). I think my issue is with syntax placement.

I’m trying to write a simple script to turn on WinRM on remote domain computers using the script below. In the output window, the computers UT0291, PD3697, and PDCM06 do not ping, but the logic drops each object into the “True” section and I don’t get the “CANNOT ping” message I expect when $tc evaluates to “false”. I’ve run the “Test-Connection” command on all 3 individually in the command window and each one returns “False”. Definitely won’t be my last post for help !! Thanks everyone.

$dcomps = get-adcomputer -filter * -SearchBase "OU=domain computers, DC=palmbayflorida, DC=org" | select name
$dcomps | ForEach {

# Set-PSDebug -Step

    $cname = $_.Name
    Write-Host "Pinging " $cname
    $tc = Test-Connection -ComputerName $cname -quiet 

    if ($tc = $true) {

        $cn = $cname + " CAN be pinged !!" 
        write-host $cn -ForegroundColor Green    
        Set-Service -Name WinRM -ComputerName $cname -StartupType Automatic -WhatIf
        get-service -Name WinRM -ComputerName $cname | Start-Service -WhatIf
    }

    else {

        $cn = $cname + " CANNOT be pinged !!"
        write-host $cn -ForegroundColor Red  
    }

    Write-Host "After 'if(tc = true)'...." $cname
}

Script Run

This should do it

$tc -eq $true

Simple mistake. The Powershell Comparison Operator is -eq, not =.

if ($tc = $true) {

should be:

if ($tc -eq $true) {

For loops, typically prefer to do loops like below versus $_ as it gets confusing what that variable context is if you are doing pipeline operations:

$dComps = 'www.google.com', 'www.badgoogle.com', 'www.microsoft.com'

foreach ($cname in $dcomps) {

    $tc = Test-Connection -ComputerName $cname -quiet -Count 2

    if ($tc -eq $true) {
        '{0} is pinging successfully' -f $cname
    }
    else {
        '{0} is pinging failed' -f $cname
    }
}

Thank you both, that did it. I’m guessing I should using the “=” type operators for arithmetic evaluations and “-eq” for boolean and string comparisons.

Rob, in your suggestions, the line "foreach ($cname in $dcomps) { ", I have seen this type of statement in many examples. However, where is the “$cname” variable declared ? Is that just some variable that is created when the statement is run ? Could I have used "foreach ($dogpile in $dcomps){ " and then reference the “$dogpile” variable ? And I assume these are variables and not objects, and therefore do not have properties, like “$cname.value” or "$dogpile.value, correct ?

Ah, to be such a newbie again, I forgot what it was like to to be “programmer dumb” !! Thanks again.

Yes, that is just a placeholder variable that is defined by you.

This is a ‘it depends’. Almost everything is an ‘object’. Even if in the exammple above you are working with strings that have properties (e.g. Length) and methods.

$dComps = 'www.google.com', 'www.badgoogle.com', 'www.microsoft.com'

foreach ($dogpile in $dcomps) {
    'Length: {0}' -f $dogpile.Length

    $dogPile.Split('.') #Split into an array
}


#foreach of a PSObject that has properties
foreach ($proc in Get-Process | Select -First 5) {
    'Processing {0} with id {1}' -f $proc.Name, $proc.Id
}

You can use GetType() to see what the type is and Get-Member to see what properties\methods exist for an object:

PS C:\Users\rasim> $dogpile.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                                                                      
-------- -------- ----                                     --------                                                                                                                                                                      
True     True     String                                   System.Object                                                                                                                                                                 



PS C:\Users\rasim> $dogpile | Get-Member


   TypeName: System.String

Name             MemberType            Definition                                                                                                                                                                                        
----             ----------            ----------                                                                                                                                                                                        
Clone            Method                System.Object Clone(), System.Object ICloneable.Clone()                                                                                                                                           
CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.CompareTo(System.Object obj), int IComparable[string].CompareTo(string other)                                     
Contains         Method                bool Contains(string value)                                                                                                                                                                       
CopyTo           Method                void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)                                                                                                                 
EndsWith         Method                bool EndsWith(string value), bool EndsWith(string value, System.StringComparison comparisonType), bool EndsWith(string value, bool ignoreCase, cultureinfo culture)                               
Equals           Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(string value, System.StringComparison comparisonType), bool IEquatable[string].Equals(string other)                        
GetEnumerator    Method                System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEnumerator(), System.Collections.Generic.IEnumerator[char] IEnumerable[char].GetEnumerator()                 
GetHashCode      Method                int GetHashCode()                                                                                                                                                                                 
GetType          Method                type GetType()                                                                                                                                                                                    
GetTypeCode      Method                System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()                                                                                                                         
IndexOf          Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf(string value), int IndexOf(string value, int startIndex), int IndexOf(string value, int startIndex, int count), i...
IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), int IndexOfAny(char[] anyOf, int startIndex, int count)                                                               
Insert           Method                string Insert(int startIndex, string value)                                                                                                                                                       
IsNormalized     Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normalizationForm)                                                                                                           
LastIndexOf      Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int LastIndexOf(string value), int LastIndexOf(string value, int startIndex), int LastIndexOf(string value, int start...
LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startIndex), int LastIndexOfAny(char[] anyOf, int startIndex, int count)                                                   
Normalize        Method                string Normalize(), string Normalize(System.Text.NormalizationForm normalizationForm)                                                                                                             
PadLeft          Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)                                                                                                                  
PadRight         Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char paddingChar)                                                                                                                
Remove           Method                string Remove(int startIndex, int count), string Remove(int startIndex)                                                                                                                           
Replace          Method                string Replace(char oldChar, char newChar), string Replace(string oldValue, string newValue)                                                                                                      
Split            Method                string[] Split(Params char[] separator), string[] Split(char[] separator, int count), string[] Split(char[] separator, System.StringSplitOptions options), string[] Split(char[] separator, int...
StartsWith       Method                bool StartsWith(string value), bool StartsWith(string value, System.StringComparison comparisonType), bool StartsWith(string value, bool ignoreCase, cultureinfo culture)                         
Substring        Method                string Substring(int startIndex), string Substring(int startIndex, int length)                                                                                                                    
ToBoolean        Method                bool IConvertible.ToBoolean(System.IFormatProvider provider)                                                                                                                                      
ToByte           Method                byte IConvertible.ToByte(System.IFormatProvider provider)                                                                                                                                         
ToChar           Method                char IConvertible.ToChar(System.IFormatProvider provider)                                                                                                                                         
ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)                                                                                                                              
ToDateTime       Method                datetime IConvertible.ToDateTime(System.IFormatProvider provider)                                                                                                                                 
ToDecimal        Method                decimal IConvertible.ToDecimal(System.IFormatProvider provider)                                                                                                                                   
ToDouble         Method                double IConvertible.ToDouble(System.IFormatProvider provider)                                                                                                                                     
ToInt16          Method                int16 IConvertible.ToInt16(System.IFormatProvider provider)                                                                                                                                       
ToInt32          Method                int IConvertible.ToInt32(System.IFormatProvider provider)                                                                                                                                         
ToInt64          Method                long IConvertible.ToInt64(System.IFormatProvider provider)                                                                                                                                        
ToLower          Method                string ToLower(), string ToLower(cultureinfo culture)                                                                                                                                             
ToLowerInvariant Method                string ToLowerInvariant()                                                                                                                                                                         
ToSByte          Method                sbyte IConvertible.ToSByte(System.IFormatProvider provider)                                                                                                                                       
ToSingle         Method                float IConvertible.ToSingle(System.IFormatProvider provider)                                                                                                                                      
ToString         Method                string ToString(), string ToString(System.IFormatProvider provider), string IConvertible.ToString(System.IFormatProvider provider)                                                                
ToType           Method                System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)                                                                                                           
ToUInt16         Method                uint16 IConvertible.ToUInt16(System.IFormatProvider provider)                                                                                                                                     
ToUInt32         Method                uint32 IConvertible.ToUInt32(System.IFormatProvider provider)                                                                                                                                     
ToUInt64         Method                uint64 IConvertible.ToUInt64(System.IFormatProvider provider)                                                                                                                                     
ToUpper          Method                string ToUpper(), string ToUpper(cultureinfo culture)                                                                                                                                             
ToUpperInvariant Method                string ToUpperInvariant()                                                                                                                                                                         
Trim             Method                string Trim(Params char[] trimChars), string Trim()                                                                                                                                               
TrimEnd          Method                string TrimEnd(Params char[] trimChars)                                                                                                                                                           
TrimStart        Method                string TrimStart(Params char[] trimChars)                                                                                                                                                         
Chars            ParameterizedProperty char Chars(int index) {get;}                                                                                                                                                                      
Length           Property              int Length {get;}  

The “flexibility” of PowerShell and it’s ability to perform the same task in a multitude of ways is a little
“mind-boggling” !! Other “rigid” languages are little easier (for me at least) to figure out and troubleshoot. Once you know
how to structure the syntax, that was pretty much it. I like the flexibility of PowerShell, it is really powerful, I just need more
practice and training…“baby steps”…although “baby steps” are at time very frustrating when you can write code in another
language with your eyes closed !!

Thanks again !!

Hi Richard,

Since you started coding in PowerShell. I can suggest you to use debug option in Powershell ISE (or other IDE which support Powershell Script Development).

It really helps you to figure out the issue.

In the above case if you have marked a breakpoint on code if ($tc = $true) {} and run the script on debug mode. When the logic reaches the line ,execute it and just hover the mouse above the $tc variable, so you can see “True” value getting assigned to the $tc variable.

So this makes you understand it is not doing the comparison.

You can learn more while debugging.!!!

 

 

Powerhell is not really a programming language, it’s a scripting platform that you can use for programming tasks, but it was built for administrators that needed to perform tasks. Programming languages are more strict because you want consistent code for the compiler or for other developers. While the rules are loose, there are style recommendations to make code easier to read, like this https://github.com/PoshCode/PowerShellPracticeAndStyle

Thanks, Rob, that makes sense. I find a lot of similarities between “script” code and “language” code. I think my biggest hurdle is going to be syntax. For example, I just watched a video which references the “Switch” function, which seems to act a lot like a “Case” statement in programming.

And thank you Sunish, I have discovered the “debug” options. In programming, the “step” function is most helpful, so I think I will find it useful as I learn.

I’m seeing that most of my work will be utilizing “WMI” and “CIM” commands to manage domain computers. We also have a Govt Office 365 tenant, so I’m delving into the world of using powershell to manage MS exchange accounts in Office 365, such as group memberships, account management etc.

Thanks again and stay tuned !!