如何在foreach中使用字符串值?
以下作品.
$printString='$_.name+","+$_.name'
Get-ChildItem|foreach {$_.name+','+$_.name}
Run Code Online (Sandbox Code Playgroud)
但以下不起作用
Get-ChildItem|foreach {$printString}
Run Code Online (Sandbox Code Playgroud)
但是我需要它才能工作:因为我有一个任务来打印表中的每一列,我可以使用表字典来获取所有列,所以都是动态的,然后当我尝试打印结果时,我也使用了像上面的字符串打印结果.任何解决方案
有几种解决方案.其中一些来自我的中间是:
$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 $_ }
Run Code Online (Sandbox Code Playgroud)
第一个扩展字符串,这可能是你想要的.请注意,必须包含组合变量$(..).第二个只是格式化一些输入.第三个使用scriptblock,你可以创建你想要的任何字符串(最强大的)
| 归档时间: |
|
| 查看次数: |
3559 次 |
| 最近记录: |