gpt4 book ai didi

sql - Powershell Get-QADUser 结果到 SQL 表

转载 作者:行者123 更新时间:2023-12-02 05:06:02 25 4
gpt4 key购买 nike

我正在使用一个字符串查询 Active Directory,该字符串循环遍历我们系统中的每个域 Controller 并返回一组结果。该脚本与 export-csv 配合使用效果很好,但因为我们希望保留自定义信息字段中的所有数据(它包含回车符),所以我想将其直接导出到 SQL 表中。

Powershell报错如下:

Exception calling "ExecuteNonQuery" with "0" argument(s): "Insert Error: Column name or >number of supplied values does not match table definition."

这是一个非常冗长的响应,我已经创建并命名了每个表的列以与 get-object 的输出完全匹配。

这是管道的输出:

SamAccountName     : testuser
DisplayName : Test User (COMPANY)
info : Test Entry 1234567890

Test for output.
Entering


Multiple lines.
whenCreated : 09/11/2004 09:08:42
whenChanged : 19/07/2012 09:25:21
AccountExpires :
pwdLastSet : 13/06/2012 07:43:43
LastLogonTimestamp : 18/07/2012 15:38:35
userAccountControl : 512
Name : Test User
LastLogon :
DC : DCNAME1

代码如下:

##--AD data output to SQL script, you need the Quest plugin!

$SamAccountName = Read-Host "Enter the username to query for last logon"

##--Query domain for all domain controllers and funnel into a forEach loop

Get-QADComputer -ComputerRole DomainController | Foreach-Object{
$dc = $_.Name

##--Query each domain controller for the user object and retrieve the LastLogon timestamp

$user = Get-QADUser -Service $dc -SamAccountName $SamAccountName -IncludedProperties info,pwdLastSet,AccountExpires,userAccountControl | Select-Object SamAccountName,displayName,info,whenCreated,whenChanged,accountExpires,pwdLastSet,lastLogonTimestamp,userAccountControl,name,LastLogon,@{n='DC';e={$dc}} |

out-host

##--Open database connection

$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=SQLSERVER; Initial Catalog=ADomain; Integrated Security=SSPI")
$conn.Open()

##--AAGH! How to grab the results of the Select-Object above?

$cmd = $conn.CreateCommand()
$cmd.CommandText ="INSERT extract VALUES ('$user')"
$cmd.ExecuteNonQuery()

##--Don't forget to close it!

$conn.Close()

现在我搞砸了一些可能很明显的事情,非常感谢任何帮助。

最佳答案

假设以下测试对象:

$exampleObject = New-Object PSObject -Property @{SamAccountName="TestSAN";DisplayName="TestDN"}

$user = $exampleObject | Select-Object SamAccountName, DisplayName

##--AAGH! How to grab the results of the Select-Object above?
$commandText = "INSERT extract VALUES ('$($user.SamAccountName)','$($user.DisplayName)'"

我还会将 sql connect 和 close 移动到循环之外,并将其放在 try/finally block 中,这样它只执行一次而不是对每个 DC 条目执行一次,并且在出现异常时仍会调用 Close在执行 try block 期间。参见 here用于在 Powershell 中使用 try/catch/finally block 的引用。

关于sql - Powershell Get-QADUser 结果到 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11647305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com