2017-10-20 74 views
1

下面的代碼讀取文件系統並返回一個JSON對象到一個php頁面,然後解析出來。Powershell腳本讀取文件系統和csv文件並返回JSON對象?

我想補充讀取csv文件

一個 「問題」 屬性「$ .FullName + 「\」 + $請將.Name + 「-questions.csv」

和返回將被嵌套在父內的JSON對象現在它返回只是一個「[」不知道爲什麼,任何幫助

Param(
    [Parameter(Mandatory = $true)][string]$path 
) 
function Add-Tabstops{ 
    param($Count) 
    $tabs = "" 
    for($i=0; $i -lt $Count; $i++){$tabs += " "} 
    return $tabs 
} 
function Read-Questions($name){ 
    $name = $name + "-questions.csv" 
    if(Test-Path($name)){ 
     $questions= Import-CSV $name | ConvertTo-JSON 
     return "[" 
       $questions 
       "]" 
    } 
    else{ 
     return "None" 
    } 
} 
function Process-Path{ 
    param($Path) 
    if (Test-Path "$path"){ 
     $source = $path.Split("\") 
     $source = $source[($source.Length -1)] 
     Output-JsonChildren -Path "$path" -Source $source 
    } 
    else { 
     return '"No Objects Found!"' 
    } 
} 

function Output-JsonChildren{ 
    param($Path, $Level = 1, $Source) 
    return $(Get-ChildItem -Path $Path -Directory | Where-Object{$_} | ForEach-Object{ 
     (Add-Tabstops $Level) + 
     "{`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Name`"`: `"$($_.Name)`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Image`"`: `"$($_.Name)`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"displayName`"`: `"$((Get-Content($($_.FullName + "\" + $_.Name + ".txt"))).split('-')[0])`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Attribute1`"`: `"$((Get-Content($($_.FullName + "\" + $_.Name + ".txt"))).split('-')[1])`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Attribute2`"`: `"$((Get-Content($($_.FullName + "\" + $_.Name + ".txt"))).split('-')[2])`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Attribute3`"`: `"$((Get-Content($($_.FullName + "\" + $_.Name + ".txt"))).split('-')[3])`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Attribute4`"`: `"$Source`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"Questions`"`: `"$(Read-Questions($($_.FullName + "\" + $_.Name)))`"," + 
     "`n" + 
     (Add-Tabstops ($Level+1)) + 
     "`"children`": ["+ 
     $(if($_.psiscontainer){"`n" + (Output-JsonChildren -Path $_.FullName -Level ($Level+2))+ "`n" + (Add-Tabstops ($Level+1))}) + 
     "]`n" + 
     (Add-Tabstops ($Level)) + 
     "}" 
    }) -join ",`n" 
} 

$JSON = Process-Path -Path $path 

"[" 
$JSON 
"]" 
+0

的文件路徑?它可以找到文件很好 – Raoul

+0

當我在單元格中放置換行符時遇到問題。也許試驗把它們拿出來? 'ConvertTo-JSON -Compress' –

回答

1

您的代碼:。。?

return "[" 
     $questions 
     "]" 

讓我們重新格式化這三條線和一些分號明確的行的結局,但留下的功能相同:

return "["; 
$questions; 
"]"; 

這是否說清楚爲什麼該函數總是返回[

你想:

return '[' + $Questions.ToString() + ']';