Powershell从json中提取数据,附加到另一个文件

时间:2018-02-12 03:06:29

标签: json windows powershell scripting

尝试创建一个脚本(无论使用哪种语言,但在这种情况下使用Powershell),如标题所示。从我的反恶意软件软件中提取数据并将阻止的网站应用到Windows黑名单。我一直在努力,但不是最有经验的PowerShell。谢谢大家的帮助!

    #This is all of the files in the folder
    $FolderContents = Get-ChildItem "C:\ProgramData\Malwarebytes\MBAMService\MwacDetections" -Filter *.json

    #Loop to go through each file individually
    for ($jsonFile=0; $jsonFile -lt $FolderContents.Count; $jsonFile++) {

     #Get the content *attempt #1*
     $x = $jsonFile | ConvertFrom-Json

     #Get the content of the file *attempt #2*
     $jsonFileContents = Get-Content $FolderContents[$jsonFile] | Out-String | ConvertFrom-Json

     #Test append
     #Add-Content C:\Users\me\Desktop\test.txt *place file content variable here*
     #REAL APPEND
     #Add-Content C:\Windows\System32\drivers\etc\hosts *place file content variable here*
    }

~~~~~~~~~~~~~~~~~~~~~~~附加照片~~~~~~~~~~~~~~~~~

单个文件和.json文件示例的错误

Error of Individual file and .json file example

数据错误的范围/深度& PowerShell版本

  

Scope/depth of data error & PowerShell version

1 个答案:

答案 0 :(得分:0)

您的代码中存在几个问题。 首先,我建议改进变量命名(参见下面的提议)。它使您的代码更易读。接下来,尝试#1将无效,因为您将for循环的索引传递给ConvertFrom-Json Cmdlet(即0 | ConvertFromJson)而不是文件的内容。最后但并非最不重要的是,调用Get-Content Cmdlet时出现的错误是因为您将文件名作为路径参数传递给Get-Content Cmdlet而不是完整文件路径。 $FolderContents[$jsonFile]只返回文件名,而不是文件的完整路径。这就是Get-Content Cmdlet在当前目录中搜索文件的原因,在您的情况下是C:\Users\me\。要解决此问题,请将文件传输到Get-Content Cmdlet($jsonFileContents = $FolderContents[$jsonFile] | Get-Content | Out-String | ConvertFrom-Json),或将文件的全名作为路径参数传递($jsonFileContents = Get-Content $FolderContents[$jsonFile].FullName | Out-String | ConvertFrom-Json)。

# All json files contained in C:\ProgramData\Malwarebytes\MBAMService\MwacDetections
$pathToMwacDetections = "C:\ProgramData\Malwarebytes\MBAMService\MwacDetections";
$jsonFiles = Get-ChildItem $pathToMwacDetections -Filter *.json

# Loop to go through each file individually
for ($index=0; $index -lt $jsonFiles.Count; $index++) {

    # Get the content of the file and convert it 
    $jsonFileContent = Get-Content $jsonFiles[$index].FullName | Out-String | ConvertFrom-Json

    #Test append
    #Add-Content C:\Users\me\Desktop\test.txt *place file content variable here*
}