将 powershell 对象转换为 CSV 中的单个字段

问题描述 投票:0回答:1

下面的代码可以完美地查看屏幕上的数据,但如果我想将其导出到 csv,则 userRules 和 Last10email 的字段为空。如何将对象 $userRules 和 $last10Email 转换为文本块,以在 CSV 中保留其格式(IE 我希望将整个表放在 CSV 的单个字段中)?我用这个戳了 GPT,但它只是让我绕圈子,提出一些不起作用的建议。

        # Get inbox rules for the user
    $userRules = Get-InboxRule -Mailbox $username | select Name, enabled, MoveToFolder, DeleteMessage, SoftDeleteMessage | Format-Table -AutoSize | Out-String

    # Get the last 10 emails for the user
    $last10EmailUTC = Get-MessageTrace -SenderAddress $User -PageSize 10 |
        Select-Object -Property Received, SenderAddress, RecipientAddress, Subject |
        Sort-Object -Property Received -Descending | Format-Table -AutoSize | Out-String

    # Convert received timestamps to local time (PST)
    $last10Email = $last10EmailUTC | ForEach-Object {
        if ($_.Received -ne $null) {
            $_.Received = $_.Received.ToLocalTime().AddHours(-8)  # Subtract 8 hours for PST
        }
        return $_
    }

# Create and return a custom object
[PSCustomObject]@{
    userPrincipalName     = $user
    SamAccountName     = $userdetails.SamAccountName
    Name                  = $userdetails.Name
    employeeId             = $userdetails.employeeId
    Enabled               = $userdetails.Enabled
    localbadPwdCount           = $userdetails.BadLogonCount
    LastlocalBadPasswordAttempt = $userdetails.LastBadPasswordAttempt
    LastLocalLogonDate         = $userdetails.LastLogonDate
    PasswordExpired       = $userdetails.PasswordExpired
    PasswordLastSet       = $userdetails.PasswordLastSet
    userRules            = $userRules
    Last10email          = $last10Email

}
powershell export-to-csv
1个回答
0
投票

我假设您以与此类似的方式输出 CSV:

$yourCustomObject | Export-Csv -Path .\filename.csv -Delimiter ','

确保设置/选择的分隔符不会出现在任何字段中。

如果这不能解决您的问题,我们将需要更多有关具体问题所在以及当前生成的一些输出的信息。

© www.soinside.com 2019 - 2024. All rights reserved.