2014-10-06 20 views
0

這是我想要實現的簡化版本...我認爲它被稱爲'可變參考'變量引用。如何創建陣列從另一個陣列的元素獲取他們的名字

我已經創建了一個包含內容的數組文件夾「富」

$myDirectory(folder1, folder2) 

使用下面的代碼:

$myDirectory= Get-ChildItem ".\foo" | ForEach-Object {$_.BaseName} 

我想創建2個數組命名爲每個文件夾,用包含文件。

folder1(file1, file2) 
folder2(file1, file2, file3) 

我嘗試下面的代碼:

foreach ($myFolder in $myDirectory) { 
    ${myFolder} = Get-ChildItem ".\$myFolders" | forEach-Object {$_.BaseName} 
} 

但顯然沒有奏效。

在bash有可能創建一個數組給它這樣的變量名:

"${myForder[@]}" 

我試圖在谷歌搜索,但我怎麼也找不到在PowerShell的

回答

0

這是我做到了底:

# Create an array containing all the folder names 
$ToursArray = Get-ChildItem -Directory '.\.src\panos' | Foreach-Object {$_.Name} 
# For each folder... 
$ToursArray | ForEach-Object { 
    # Remove any variable named as the folder's name. Check if it exists first to avoid errors 
    if(Test-Path variable:$_.BaseName){ Remove-Variable -Name $_.BaseName } 
    $SceneName=Get-ChildItem ".\.src\panos\$_\*.jpg" 
    # Create an array using the main folder's name, containing the names of all the jpg inside 
    New-Variable -Name $_ -Value ($SceneName | Select -ExpandProperty BaseName) 
} 

而且這裏去一些代碼來檢查所有數組的內容:

# Print Tours information 
Write-Verbose "Virtual tours list: ($($ToursArray.count))" 
$ToursArray | ForEach-Object { 
Write-Verbose " Name: $_" 
Write-Verbose " Scenes: $($(Get-Variable $_).Value)" 

}

輸出:

VERBOSE: Name: tour1 
VERBOSE:  Scenes: scene1 scene2 
VERBOSE: Name: tour2 
VERBOSE:  Scenes: scene1 
1
$myDirectory = "c:\temp" 
Get-ChildItem $myDirectory | Where-Object{$_.PSIsContainer} | ForEach-Object{ 
     Remove-Variable -Name $_.BaseName 
     New-Variable -Name $_.BaseName -Value (Get-ChildItem $_.FullName | Where-Object{!$_.PSIsContainer} | Select -ExpandProperty Name) 
    } 
做到這一點

我認爲你要找的是New-Variable。循環瀏覽C:\temp下的所有文件夾。爲每個文件夾創建一個新變量。如果變量已經存在,它會拋出錯誤。你可以做的是去除一個預先存在的變量。使用Get-ChildItem使用管道中的當前文件夾內容填充變量。以下是如何生成新變量的-Value的小解釋。 注意事項Remove-Variable根據您的文件夾名稱有機會刪除意外的變量。不確定這會帶來什麼影響。

Get-ChildItem $_.FullName | Where-Object{!$_.PSIsContainer} | Select -ExpandProperty Name 

每個自定義變量的值是每個文件(不是文件夾)。使用-ExpandProperty僅將字符串的名稱設置爲與Name s對應的對象。

除了

你打算使用這些數據的是什麼?將輸出從Get-ChildItem輸出到另一個cmdlet可能會更容易。或者用你想要的數據創建一個自定義對象。

從評論

$myDirectory = "c:\temp" 
Get-ChildItem $myDirectory | Where-Object{$_.PSIsContainer} | ForEach-Object{ 
     [PSCustomObject] @{ 
      Hotel = $_.BaseName 
      Rooms = (Get-ChildItem $_.FullName | Where-Object{!$_.PSIsContainer} | Select -ExpandProperty Name) 
     } 

    } 

您需要爲上述工作至少PowerShell的3.0更新。如果需要,將它更改爲2.0很容易。創建並反映酒店名稱和「房間」,這是文件夾內的文件名稱。如果你不想要擴展只使用BaseName而不是Name在選擇。

+0

該數據是爲你創建一些xml文件在網站上。基本上每個文件夾都是酒店,其內容(jpg文件)是房間。在這個階段,我認爲必須有更好更簡單的方法來做到這一點。也許是一個包含2個數組的數組(每個酒店都有一個數組),並且每個數組都包含房間名稱。 – RafaelGP 2014-10-07 12:46:35

+0

@RafaelGP通過簡單的更改更新了答案 – Matt 2014-10-07 13:04:30

相關問題