![](/img/trans.png)
[英]Add/Append a new key-value pair in JSON after reading from another JSON file in PowerShell
[英]Powershell Pull data from json, append to another file
尝试创建脚本(与哪种语言无关,但在这种情况下使用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文件示例的错误
数据错误的范围/深度和PowerShell版本
您的代码中有几个问题。 首先,我建议改进变量命名(请参阅下面的建议)。 它使您的代码更具可读性。 接下来,由于将for循环的索引通过管道传递到ConvertFrom-Json
Cmdlet(即0 | ConvertFromJson
)而不是文件内容,因此尝试#1将不起作用。 最后但并非最不重要的一点是,在调用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*
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.