如何使用PowerShell添加从SQL Server的数据添加数据?

发布于 2025-02-06 14:41:46 字数 1385 浏览 1 评论 0 原文

基本上,我希望数据显示在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"

Basically, I want the data to show up in an excel file like it shows in the SQL database.
This is much more simplified version of the work that I need to do but in essence this what it is.

I retrieve the data from SQL and for each item retrieved(which is the primary key) I want the data corresponding to it to be added in the hashtable. I then export this hashtable as a CSV

The CSV file is generated but with some weird data

enter image description here

I am not sure what exactly is wrong because when I Write-host $hashObject I can see the data is in there.

Code

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

櫻之舞 2025-02-13 14:41:46

这是您尝试做的事情的简化版本,在这种情况下,您应该能够使用操作员中的SQL 在您的第二个查询中,而不是在每个循环迭代中查询数据库。

顺便说一句,尚不清楚您在声明哈希表然后将其转换为 pscustomObject 实例然后将其包装在 arnay> array> array

$hashTable  = @{}
$hashObject = @([PSCustomObject] $hashTable)

也值得注意<< 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字符串,然后将它们导出到文件。

$server     = "DESKTOP\SQLEXPRESS"
$database   = "AdventureWorks2019"
$query      = "SELECT [DepartmentID] FROM [AdventureWorks2019].[HumanResources].[Department]"
$invokeSql  = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query
$department = "'{0}'" -f ($invokeSql.DepartmentID -join "','")
$query      = @"
SELECT [Name],
       [GroupName],
       [ModifiedDate]
FROM [AdventureWorks2019].[HumanResources].[Department]
WHERE DepartmentID IN ($department);
"@

Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query |
    Export-Csv -Path "C:\Users\Desktop\PowerShell\HashTable_OutputFiles\HashOutput.csv"

如果您想从第一个查询查询每个ID的数据库,则可以这样做(请注意,这类似于您想要完成的工作,将 id 与第二个结果合并。询问):

$invokeSql = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query
$query     = @"
SELECT [Name],
       [GroupName],
       [ModifiedDate]
FROM [AdventureWorks2019].[HumanResources].[Department]
WHERE DepartmentID = '{0}';
"@

& {
    foreach($id in $invokeSql.DepartmentID) {
        $queryID = $query -f $id
        Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $queryID |
            Select-Object @{ N='DepartmentID'; E={ $id }}, *
    }
} | Export-Csv -Path "C:\Users\Desktop\PowerShell\HashTable_OutputFiles\HashOutput.csv"

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:

$hashTable  = @{}
$hashObject = @([PSCustomObject] $hashTable)

It's also worth noting that ConvertTo-Csv and Import-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 when Import-Csv can (and in this case, must) receive the objects, convert them to a Csv string and then export them to a file.

$server     = "DESKTOP\SQLEXPRESS"
$database   = "AdventureWorks2019"
$query      = "SELECT [DepartmentID] FROM [AdventureWorks2019].[HumanResources].[Department]"
$invokeSql  = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query
$department = "'{0}'" -f ($invokeSql.DepartmentID -join "','")
$query      = @"
SELECT [Name],
       [GroupName],
       [ModifiedDate]
FROM [AdventureWorks2019].[HumanResources].[Department]
WHERE DepartmentID IN ($department);
"@

Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query |
    Export-Csv -Path "C:\Users\Desktop\PowerShell\HashTable_OutputFiles\HashOutput.csv"

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):

$invokeSql = Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $query
$query     = @"
SELECT [Name],
       [GroupName],
       [ModifiedDate]
FROM [AdventureWorks2019].[HumanResources].[Department]
WHERE DepartmentID = '{0}';
"@

& {
    foreach($id in $invokeSql.DepartmentID) {
        $queryID = $query -f $id
        Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $queryID |
            Select-Object @{ N='DepartmentID'; E={ $id }}, *
    }
} | Export-Csv -Path "C:\Users\Desktop\PowerShell\HashTable_OutputFiles\HashOutput.csv"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文