【发布时间】:2017-05-12 22:21:19
【问题描述】:
我有一个 PowerShell 脚本,它提取 1.4+ 百万行数据并将其保存到一个巨大的 CSV 文件中,然后将其导入 SQL 服务器。我认为可能有一种方法可以让 PowerShell 直接将数据插入 SQL 服务器,但我不确定如何。
我担心的一个问题是我不想将 AD 结果缓冲到内存中然后再写入它们。我宁愿分批写 1000 个或其他东西,这样内存消耗就会下降。获取 1000 条记录,保存到 SQL Server,然后重复...
我看到有关如何让 PowerShell 写入 SQL 服务器的文章,但它们似乎要么一次处理所有数据,要么一次处理一条记录——这两种方法对我来说似乎都效率低下。
这是我必须查询 AD 的 PowerShell 脚本。
# the attributes we want to load
$ATTRIBUTES_TO_GET = "name,distinguishedName"
# split into an array
$attributes = $ATTRIBUTES_TO_GET.split(",")
# create a select string to be used when we want to dump the information
$selectAttributes = $attributes | ForEach-Object {@{n="AD $_";e=$ExecutionContext.InvokeCommand.NewScriptBlock("`$_.$($_.toLower())")}}
# get a directory searcher to search the GC
[System.DirectoryServices.DirectoryEntry] $objRoot = New-Object System.DirectoryServices.DirectoryEntry("GC://dc=company,dc=com")
[System.DirectoryServices.DirectorySearcher] $objSearcher = New-Object System.DirectoryServices.DirectorySearcher($objRoot)
# set properties
$objSearcher.SearchScope = "Subtree"
$objSearcher.ReferralChasing = "All"
# need to set page size otherwise AD won't return everything
$objSearcher.PageSize = 1000
# load the data we want
$objSearcher.PropertiesToLoad.AddRange($attributes)
# set the filter
$objSearcher.Filter = "(&(objectClass=group)(|(name=a*)(name=b*)))"
# get the data and export to csv
$objSearcher.FindAll() | select -expandproperty properties | select $selectAttributes | export-csv -notypeinformation -force "out.csv"
【问题讨论】:
-
考虑批量使用SqlBulkCopy。 stackoverflow.com/questions/43679921/…
-
我认为bulk insert 的效率差不多。你为什么不相信?
-
@DanGuzman 但是我将如何使用
System.DirectoryServices.SearchResultCollection对象批量执行此操作?我能想到的唯一方法是遍历SearchResultCollection并在 X # 条记录之后进行批量 SQL 插入? -
@AnsgarWiechers 我不反对。我只是不知道如何使用
SearchResultCollection对象进行批量插入,而无需将整个集合加载到内存中。
标签: sql-server powershell active-directory