我正在尝试删除几个文件夹的内容。我有什么:
$Config = @{
InstallPath = 'C:Program FilesApp'
SubPaths = @('wwwapp1', 'wwwapp2', 'wwwapp3')
}
这是获取内容的代码:
$Config.SubPaths | Select-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
但它不起作用,因为Get-ChildItem
接收如下对象:
@{ Join-Path $Config.InstallPath $_ =C:Program FilesAppwwwapp1}
错误:
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
应该绑定到正在制作的新对象的 path 属性