Powershell Select-Object如何获得值数组
问题描述:
我想删除几个文件夹的内容。 我有什么:Powershell Select-Object如何获得值数组
$Config = @{
InstallPath = 'C:\Program Files\App'
SubPaths = @('www\app1', 'www\app2', 'www\app3')
}
这里是代码来获取内容:
$Config.SubPaths | Select-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
但它不工作,因为Get-ChildItem
接收对象象下面这样:
@{ Join-Path $Config.InstallPath $_ =C:\Program Files\App\www\app1}
错误:
Get-ChildItem : Cannot find drive. A drive with the name '@{ Join-Path $Config.InstallPath $_ =C' does not exist.
At line:1 char:85
+ ... elect-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (@{ Join-Path $C...stallPath $_ =D:String) [Get-ChildItem], DriveNotFoun
dException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
如何将Select-Object
的结果转换为简单的字符串数组?或者使代码更好的其他方法?
答
您得到的结果是因为您用文字属性Join-Path $Config.InstallPath $_
创建了一个新对象。相反...
$Config.SubPaths | ForEach-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
您并未试图选择单个子路径的属性,而是从每个子路径生成一个字符串。使用Foreach-object
代替迭代集合应该可以得到您正在查找的结果。
尽管您可以使用计算属性创建自定义对象和属性,但我认为这不是您要使用的方向。但是,为了回答标题中的问题,你可以这样做:
$Config.SubPaths |
Select-Object @{Name="Path";Expression={Join-Path $Config.InstallPath $_}} |
Get-ChildItem
Get-ChildItem
应该绑定到新的对象的路径属性都正在
+0
谢谢,这是我想要的。 – Zergatul
'$ Config.SubPaths | ForEach-Object {Join-Path $ Config.InstallPath $ _} | Get-ChildItem' – Matt