0

I cannot seem to find anything about using the values of one property of an object in a foreach loop (without having the entire object placed into the loop).

I first create a function called UFGet-Servers that uses Get-ADComputer and returns the names of the servers in a specific OU in my environment and places them in an array. That's great, except that when I use the array in a foreach loop, each object that it grabs has @[Name=serverName] in it, which I cannot use in any useful manner. The following pseudo-code is an abbreviated example:

foreach($Computer in $ComputerNames){do code... code is adding the server name into a UNC path such as "\\$Computer\C$\"}

The problem with the above is that you can't add the whole object to a path -- it ends up looking like "\@[Name=serverNameHere]\C$\" which totally bombs out. How do I get rid of the "@[property=" part, and simply use the value as the $Computer in the loop?

What really weirds me out is that I can't find a straightforward article on this anywhere... would have thought everyone and their mom would have wanted to do something like this.

1
  • Sounds like your function actually returns an array of hashtables instead of an array of strings. Try referring to $Computer.Name or $Computer.Item('Name') or $Computer['Name']. Commented Jan 6, 2015 at 19:03

1 Answer 1

2

So, your issue isn't with ForEach loops, it is with string formatting. There are two ways that I know of to take care of what you need. First is going to be string formatting, which allows you to use {0}m {1} and so on to inject values into a string, providing that you follow the string with -f and a list of said values. Such as:

ForEach($Computer in $ComputerNames){
    "The Server Path is \\{0}\Share$" -f $Computer.Name
}

The second way is a sub-expression (I'm sure somebody will correct me if I used the wrong term there). This one involves enclosing the variable and desired property (or a function, or whatever) inside $(). This will evaluate whatever is inside the parenthesis before evaluating the string. See my example:

ForEach($Computer in $ComputerNames){
    "The Server Path is \\$($Computer.name)\Share$"
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like the latter option the best. Thanks! I new something like this had to exist, but I am, quite frankly, a noob, so this really helped. Whole script works now (and that was the last problem section of a larger script).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.