使用PowerShell将Chrome书签导出为CSV文件

时间:2017-11-17 07:44:20

标签: json powershell google-chrome bookmarks powershell-v5.0

我正在尝试使用Powershell将Chrome书签导出为CSV / Excel。关于正在创建的错误JSON文件,我正在遇到障碍。这是因为Chrome中有两组名为 Bookmark_Bar 同步的文件夹。

BookMark_Bar创建一个带括号的JSON,如下所示:

[
{

},
{

}
]

同步文件夹还会在同一文件中创建一组数据:

[
{

},
{

}
]

代码如下。

$isodate = Get-Date -Format yyyymmmdd_hhmmss
$logFilePath = "d:\PowerShell_$isodate.log"
# ############################
Start-Transcript -Path $logFilePath -Append
#########################################

#Declare Variables

$pathToJsonFile = "$env:localappdata\Google\Chrome\User Data\Default\Bookmarks"
#$JsonFilePath = "D:\04. PowerShell\BookMarks\ChromeBookMarx.json"
#$OutputFilePath = "D:\BookMarx.csv" 

$data = Get-content $pathToJsonFile | out-string | ConvertFrom-Json

Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"


#A nested function to enumerate bookmark folders
Function Get-BookmarkFolder {
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$True)]
$Node
)

Process 
{

 foreach ($child in $node.children) 
 {
   #get parent folder name
   $parent = $node.Name
   if ($child.type -eq 'Folder') 
   {
     Write-Verbose "Processing $($child.Name)"
     Get-BookmarkFolder $child
   }
   else 
   {
        $hash= [ordered]@{
          Folder = $parent
          Name = $child.name
          URL = $child.url
          Added = [datetime]::FromFileTime(([double]$child.Date_Added)*10)
        }
      #write custom object
        New-Object -TypeName PSobject -Property $hash
  } #else url
 } #foreach
 } #process
} #end function

#create a new JSON file
$text | Set-Content 'file.json'
$test1 = '{
  "markers":' | Add-Content 'file.json'

#these should be the top level "folders"
$data.roots.bookmark_bar | Get-BookmarkFolder |ConvertTo-Json |Add-Content 'D:\file.json'
$data.roots.other | Get-BookmarkFolder  |ConvertTo-Json |Add-Content 'D:\file.json'
$data.roots.synced | Get-BookmarkFolder  |ConvertTo-Json |Add-Content 'D:\file.json'

$EndBraceClose = ']}' | Add-Content 'file.json'

Get-Content 'D:\file.json' -Raw |
ConvertFrom-Json | select -ExpandProperty markers|
Export-CSV $env:USERPROFILE\desktop\ChromeBookMarx_$isodate.csv -NoTypeInformation

    # end logging 
    ###########################
    Stop-Transcript
    ###########################

JSON文件的结果如下所示: -

{
  "BookMarks":
[
    {
        "Folder":  "Sanddance",
        "Name":  "Microsoft Garage",
        "URL":  "https://www.microsoft.com/en-us/garage/workbench/",
        "Added":  "\/Date(1504585556230)\/"
    },
    {
        "Folder":  "Sanddance",
        "Name":  "Microsoft has a new data visualization tool you can use for free",
        "URL":  "https://thenextweb.com/",
        "Added":  "\/Date(1504584050296)\/"
    }
]
[
   {
        "Folder":  "Amazon",
        "Name":  "Cycling Equipment: Buy Cycling Accessories, Bike Tools \u0026 Equipment Online at Low Prices in India",
        "URL":  "https://www.amazon.in/",
        "Added":  "\/Date(1504859500323)\/"
    },

    {
        "Folder":  "Other bookmarks",
        "Name":  "Zakir Khan-Fan Honge Dusron Ke Apne To Dost Hote Hai - YouTube",
        "URL":  "https://www.youtube.com/watch?v=n4WKiwhn29o",
        "Added":  "\/Date(1497416694729)\/"
    }
]
]
}

第16和17行的括号似乎导致了问题。我需要一些帮助来纠正所写的代码。

3 个答案:

答案 0 :(得分:1)

如果您看一下JSON示例的基本结构,则没有[] http://json.org/example.html

所以我稍微调整了你的脚本我的Chrome路径与你的不同,所以你必须改变它。

    $isodate = Get-Date -Format yyyymmmdd_hhmmss
$file = "C:\temp\file.json"
#Declare Variables

$pathToJsonFile = "$env:localappdata\Google\Chrome\User Data\Profile 1\Bookmarks"
#$JsonFilePath = "D:\04. PowerShell\BookMarks\ChromeBookMarx.json"
#$OutputFilePath = "D:\BookMarx.csv" 

$data = Get-content $pathToJsonFile | out-string | ConvertFrom-Json

Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"


#A nested function to enumerate bookmark folders
Function Get-BookmarkFolder {
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$True)]
$Node
)

Process 
{

 foreach ($child in $node.children) 
 {
   #get parent folder name
   $parent = $node.Name
   if ($child.type -eq 'Folder') 
   {
     Write-Verbose "Processing $($child.Name)"
     Get-BookmarkFolder $child
   }
   else 
   {
        $hash= [ordered]@{
          Folder = $parent
          Name = $child.name
          URL = $child.url
          Added = [datetime]::FromFileTime(([double]$child.Date_Added)*10)
        }
      #write custom object
        New-Object -TypeName PSobject -Property $hash
  } #else url
 } #foreach
 } #process
} #end function

#create a new JSON file
$text | Set-Content $file -Force
$test1 = '{
  "markers":' | Add-Content $file

#these should be the top level "folders"
$data.roots.bookmark_bar | Get-BookmarkFolder |ConvertTo-Json |Add-Content $file
$data.roots.other | Get-BookmarkFolder  |ConvertTo-Json |Add-Content $file
$data.roots.synced | Get-BookmarkFolder  |ConvertTo-Json |Add-Content $file

 '}' | Add-Content $file

Get-Content $file -Raw |
ConvertFrom-Json | select -ExpandProperty markers|
Export-CSV $env:USERPROFILE\desktop\ChromeBookMarx_$isodate.csv -NoTypeInformation

这为我在桌面上提供了一个有效的CSV文件。有趣的想法顺便说一句。

所以这条线是我发现的最大问题:

$EndBraceClose = ']}' | Add-Content 'file.json'

答案 1 :(得分:1)

$isodate = Get-Date -Format yyyymmmdd_hhmmss
$pathToJsonFile = "$env:localappdata\Google\Chrome\User Data\Default\Bookmarks"
$data = Get-content $pathToJsonFile | out-string | ConvertFrom-Json

#A nested function to enumerate bookmark folders
Function Get-BookmarkFolder {
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$True)]
$Node
)

Process 
{

 foreach ($child in $node.children) 
 {
   #get parent folder name
   $parent = $node.Name
   if ($child.type -eq 'Folder') 
   {
     Write-Verbose "Processing $($child.Name)"
     Get-BookmarkFolder $child
   }
   else 
   {
        $hash= [ordered]@{
          Folder = $parent
          Name = $child.name
          URL = $child.url
          Added = [datetime]::FromFileTime(([double]$child.Date_Added)*10)
        }
      #write custom object
        New-Object -TypeName PSobject -Property $hash
  } #else url
 } #foreach
 } #process
} #end function


$data = Get-content $pathToJsonFile -Encoding UTF8 | out-string | ConvertFrom-Json
$sections = $data.roots.PSObject.Properties | select -ExpandProperty name
$output = ForEach ($entry in $sections) {
    $data.roots.$entry | Get-BookmarkFolder
}
$output | Export-CSV $env:USERPROFILE\desktop\ChromeBookMarx_$isodate.csv -NoTypeInformation

提起一个旧的文件,但是我没有临时的json文件。

答案 2 :(得分:0)

在此期间不确定ConvertTo-Json是否有任何变化。

这是我的拍摄,另外输出每个书签的文件夹路径,并按照我想要的方式格式化日期时间:

#Path to chrome bookmarks
$pathToJsonFile = "$env:localappdata\Google\Chrome\User Data\Default\Bookmarks"

#Helper vars
$temp = "C:\temp\google-bookmarks.json"
$timestamp = Get-Date -Format yyyymmmdd_hhmmss

$global:bookmarks = @()

#A nested function to enumerate bookmark folders
Function Get-BookmarkFolder {
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$True)]
$Node
)

Process 
{

 foreach ($child in $node.children) 
 {
   #get parent folder name
   $parent = $node.Name
   $folder = If (!$node.Folder) {""} Else {$node.Folder}
   $folder = $folder + $parent + "/" 
   $child | Add-Member @{Folder= $folder}
   if ($child.type -eq 'Folder') 
   {
     # Write-Verbose "Processing $($child.Name)"
     Get-BookmarkFolder $child
   }
   else 
   {
        $hash= [ordered]@{
          Folder = $parent
          Name = $child.name
          URL = $child.url
          Path = $child.folder.substring(0,$child.folder.Length-1)
          Added = "{0:yyyyMMddHHmmssfff}" -f [datetime]::FromFileTime(([double]$child.Date_Added)*10)
        }
        #add ascustom object to collection
        $global:bookmarks += New-Object -TypeName PSobject -Property $hash
  } #else url
 } #foreach
 } #process
} #end function

$data = Get-content $pathToJsonFile -Encoding UTF8 | out-string | ConvertFrom-Json

#process top level "folders"
$data.roots.bookmark_bar | Get-BookmarkFolder
$data.roots.other | Get-BookmarkFolder
$data.roots.synced | Get-BookmarkFolder

#create a new JSON file
$empty | Set-Content $temp -Force
'{
"bookmarks":' | Add-Content $temp

#these should be the top level "folders"
$global:bookmarks | ConvertTo-Json | Add-Content $temp

'}' | Add-Content $temp

Write-Verbose $temp

Get-Content $temp -Raw |
ConvertFrom-Json |
select -ExpandProperty bookmarks |
Export-CSV $env:USERPROFILE\Desktop\ChromeBookmarks_$timestamp.csv -NoTypeInformation

Remove-Item $temp

请注意我使用全局数组首先收集所有书签,以避免任何多余的尖括号[]为我打破Snak3d0ccode