我正在使用DBATools Module Invoke-DBQQuery(基于Invoke-SQLCMD2(来查询SQL数据库。 该查询以名为 $Results 的 PSObject 形式返回单个记录,如下所示...
FileName : C12345
BADGENUMBER : BADGENUMBER=12345
LASTNAME : LASTNAME=SMITH
FIRSTNAME : FIRSTNAME=JOHN
CIA : CIA=YES
SOCIALSECURITY : SOCIALSECURITY=999999999
DACDATE : DACDATE=07/16/2022
UIC : UIC=42158
我需要将此 PSObject 输出到仅值为 no 的 TXT 文件 字段标题 每行一个字段。看起来像这样...
C12345
BADGENUMBER=12345
LASTNAME=SMITH
FIRSTNAME=JOHN
CIA=YES
SOCIALSECURITY=999999999
DACDATE=07/16/2022
UIC=42158
如何以所需的格式生成测试文件?
$Results| Out-File c:test.test.txt
生成我列出的第一个输出。
感谢任何人都可以提供的任何帮助。
-马克-
这里有一些不同的角度需要解决
$result = Invoke-DbaQuery -SqlInstance $sql -Query 'select * from MyTable' -As PSObject
# Simulate a 2 rows result
$result = [PSCustomObject]@{
FileName = 'C12345'
BADGENUMBER = 'BADGENUMBER=12345'
LASTNAME = 'LASTNAME=SMITH'
FIRSTNAME = 'FIRSTNAME=JOHN'
CIA = 'CIA=YES'
SOCIALSECURITY = 'SOCIALSECURITY=999999999'
DACDATE = 'DACDATE=07/16/2022'
UIC = 'UIC=42158'
},[PSCustomObject]@{
FileName = 'C12345'
BADGENUMBER = 'BADGENUMBER=12345'
LASTNAME = 'LASTNAME=SMITH'
FIRSTNAME = 'FIRSTNAME=JOHN'
CIA = 'CIA=YES'
SOCIALSECURITY = 'SOCIALSECURITY=999999999'
DACDATE = 'DACDATE=07/16/2022'
UIC = 'UIC=42158'
}
# Using RegEx -replace to remove the front part
($result | Out-String) -replace '(?m)^[ws]+:s','' | Out-File C:Temptest1.txt
# Looping for every properties (they will get reordered by property name)
# I just saw Mathias suggestion and it would produce the same result
$result | Get-Member -Type NoteProperty | ForEach-Object {$result.($_.Name)} | Out-File C:Temptest2.txt
# Simplier solution
$output = foreach ($row in $result) {
$row.FileName
$row.BADGENUMBER
$row.LASTNAME
$row.FIRSTNAME
$row.CIA
$row.SOCIALSECURITY
$row.DACDATE
$row.UIC
"" # you probably want to have an empty row seperating each record
}
$output | Out-File C:Temptest3.txt