1

我正在使用 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 输出到一个 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 

产生我列出的第一个输出。

感谢任何人可以提供的任何帮助。

-标记-

4

1 回答 1

0

这里有一些不同的角度来解决

$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)^[\w\s]+:\s','' | Out-File C:\Temp\test1.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:\Temp\test2.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:\Temp\test3.txt
于 2021-12-10T05:15:20.120 回答