2017-10-20 94 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() + ']';