2

我想将我的脚本结果导出到一个新的 CSV 文件。不幸的是,Export-Csv唯一的创建一个空文件。我认为Write-Host无法将其保存到文件中存在问题?

也许有一个选项可以将控制台的输出保存到 txt/csv 文件。

$Date = $((Get-Date).ToString('yyyy-MM-dd'))

$Evaluation = {
    $Users = Get-ADUser -Filter 'enabled -eq $true' -SearchBase $OU -Properties mailNickname

    Write-Host "Name;CAL Exchange"

    foreach ($User in $Users) {
        if ($User.mailNickName -eq $null) {
            $User.CALEX = "No"
        } else {
            $User.CALEX = "Yes"
        }
        Write-Host "$($User.Name);$($User.CALEX)"
    }
    Write-Host ""
    Write-Host "Count: $($Users.Count) Users"
}

$Evaluation_Department = {
    $OU = "OU=ofDepartment"
    & $Evaluation | Export-Csv -Path "C:\Support\$($Date)-Department.csv"
}
& $Evaluation_Department

我除了这个在文件中:

名称;CAL 交换
$($User.Name);$($User.CALEX)
[...]
$($User.Name);$($User.CALEX)

计数:$($Users.Count) 个用户

& $Evaluation_Department只是为了测试目的。

4

2 回答 2

1

The desired file can be generated by a simplified version of your script:

$Date = $((Get-Date).ToString('yyyy-MM-dd'))
$OU = "OU=ofDepartment"

$Users = Get-ADUser -Filter 'enabled -eq $true' -SearchBase $OU -Properties mailNickname
$Users | Select-Object Name,@{name="CAL Exchange";e={if($User.mailNickName) {return "Yes"} else {return "No"}}} | Export-CSV -Path "C:\temp\$($Date)-Department.csv" -NoTypeInformation

Of course it wouldn't have Count: X Users at the end, but I removed this on purpose - personally I'd not put this in .csv file. You can add this easily by using Add-Content.


NOTE: Be careful with data format while adding content manually to CSV file - otherwise it might become not readable by Excel for example. Usually, you'll have to remember about "

于 2019-10-10T09:04:13.930 回答
0

I think this is what you're looking for

$date = $((Get-Date).ToString('yyyy-MM-dd'))    
$OU = "OU=_Users,CN=..."

$Users = Get-ADUser -Filter 'enabled -eq $true' -SearchBase = $OU -Properties mailNickname

$Users | Add-Member -MemberType NoteProperty -Name CALEX -Value $null -Force

foreach ($User in $Users)
{
    if ($User.mailNickName -eq $null)
    {
        $User.CALEX = "No"
    }
    else
    {
        $User.CALEX = "Yes"
    }
}    

$Users | Select-Object SamAccountName, CALEX | Export-CSV -Path "C:\Support\$($Date)-Department.csv" -NoTypeInformation -Force
于 2019-10-10T09:02:40.897 回答