Daniel Wu
Daniel Wu

Reputation: 6003

How to use a string value in foreach?

How to use a string value in foreach?

The following works.

$printString='$_.name+","+$_.name'
Get-ChildItem|foreach {$_.name+','+$_.name}

But the following doesn't work

Get-ChildItem|foreach {$printString}

But I need it to work: because I have a task to print each column in a table, I can use table dictionary to get all the columns, so all are dynamic, and then when I try to print the result, I also use a string like above to print the result. Any solution

Upvotes: 1

Views: 4793

Answers (4)

stej
stej

Reputation: 29449

There are several solutions. Some of them that came on my mid are:

$printString='$($_.name),$($_.name)'
Get-ChildItem | % { $ExecutionContext.InvokeCommand.ExpandString($printString) }

$formatString='{0},{0}'
Get-ChildItem | % { $formatString -f $_.Name }

$s = {param($file) $file.Name + "," + $file.Name }
Get-ChildItem | % { & $s $_ }

The first one expands string and that's probably what you wanted. Note that composed variables have to be enclosed in $(..). The second just formats some input. The third uses scriptblock there you can create any string you want (the most powerfull)

Upvotes: 6

Doug Finke
Doug Finke

Reputation: 6823

Interesting possibility:

dir | select @{Name='Name'; Expression={$_.Name, $_.Name}}

Upvotes: 0

OldFart
OldFart

Reputation: 2479

Another possible solution:

$printString='$_.name+","+$_.name'
Get-ChildItem|foreach { Invoke-Expression $printString }

Upvotes: 2

mjolinor
mjolinor

Reputation: 68243

One possible solution:

 $printString={$_.name+","+$_.name}
 Get-ChildItem |foreach {.$printString}

Upvotes: 2

Related Questions