2017-10-06 52 views
1

我想刪除幾個文件夾的內容。 我有什麼: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的結果轉換爲簡單的字符串數組?或者使代碼更好的其他方法?

+0

'$ Config.SubPaths | ForEach-Object {Join-Path $ Config.InstallPath $ _} | Get-ChildItem' – Matt

回答

1

您得到的結果是因爲您用文字屬性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