如何使用PowerShell添加从SQL Server的数据添加数据?
基本上,我希望数据显示在SQL数据库中显示的Excel文件中。 这是我需要做的工作的简化版本,但本质上是它的本质。
我从SQL中检索数据,对于检索到的每个项目(这是主要的键),我希望与其相对应的数据添加在Hashtable中。然后,我将此hashtable导出为CSV,
生成了CSV文件,但是有一些怪异的数据
://i.sstatic.net/l6b6p.png“ alt =“在此处输入图像说明”>
我不确定到底是什么问题可以看到数据在其中。
代码
$server = "DESKTOP\SQLEXPRESS"
$database = "AdventureWorks2019"
$hashTable = @{}
$hashObject = @([PSCustomObject]$hashTable)
$query = "SELECT[DepartmentID] FROM [AdventureWorks2019].[HumanResources].[Department]"
$invokeSql = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query
$departmentResult = $invokeSql.DepartmentID
ForEach($department in $departmentResult){
$queryAll = "SELECT [Name],[GroupName],[ModifiedDate]FROM [AdventureWorks2019].[HumanResources].[Department] Where DepartmentID=$department"
$invokeSql = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $queryAll
$name = $invokeSql.Name
$groupName = $invokeSql.GroupName
$modifiedDate = $invokeSql.ModifiedDate
$hashObject+=("Department",$department, "Name",$name,"GroupName",$groupName,"ModifiedDate",$modifiedDate)
}
ConvertTo-Csv $hashObject| Export-Csv -Path "C:\Users\Desktop\PowerShell\HashTable_OutputFiles\HashOutput.csv"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您尝试做的事情的简化版本,在这种情况下,您应该能够使用操作员中的SQL 在您的第二个查询中,而不是在每个循环迭代中查询数据库。
顺便说一句,尚不清楚您在声明哈希表然后将其转换为
pscustomObject
实例然后将其包装在 arnay> array> array :也值得注意<< a href =“ https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-csv?view = powershell-7.2” csv 和
import-csv
的编码方式是打算从管道中接收对象的方式。 这个答案可能有助于澄清为什么。还不清楚为什么您要首先尝试将对象转换为CSV,然后在import-csv
可以(在这种情况下,必须)接收对象时,将它们转换为CSV,然后将其导出。它们到CSV字符串,然后将它们导出到文件。如果您想从第一个查询查询每个ID的数据库,则可以这样做(请注意,这类似于您想要完成的工作,将 id 与第二个结果合并。询问):
This is a simplified version of what you're attempting to do, in this case you should be able to use the SQL IN Operator in your second query instead of querying your Database on each loop iteration.
As aside, is unclear what you wanted to do when declaring a hash table to then convert it to a
PSCustomObject
instance and then wrap it in an array:It's also worth noting that
ConvertTo-Csv
andImport-Csv
are coded in such a way that they are intended to receive objects from the pipeline. This answer might help clarifying the Why. It's also unclear why are you attempting to first convert the objects to Csv and then exporting them whenImport-Csv
can (and in this case, must) receive the objects, convert them to a Csv string and then export them to a file.If you want to query the database per ID from the first query, you could do it this way (note this is similar to what you where looking to accomplish, merge the ID with the second results from the second query):