Powershell:如何在屏幕上显示输出并输出到文件



希望您能提供帮助。PS非常新,所以请耐心等待:(

我对下面的脚本有问题。如果我把"输出文件"命令放在第6行,结果会打印在powershell屏幕上,但txt文件是空白的。如果我将"输出文件"命令放在第3行的末尾,则会填充文本文件,但它不会在powershell窗口中输出结果。我希望它同时做这两件事。令人沮丧:(

import-module activedirectory
$username = Read-Host 'Please enter Username!'
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties * | select name, description | Format-Table -Wrap -AutoSize
$wsh = New-Object -ComObject Wscript.Shell
$wsh.Popup("List has been saved to C:Group_List.txt")
Out-File C:Group_List.txt
Read-Host -Prompt "Press Enter to exit"

您可以使用Tee-Object(受经典teeunix命令行工具的启发(将输入流派生到磁盘上的变量或文件中!如果您想按原样将格式化的表写入文件,只需将其粘贴到输出到屏幕的管道表达式的末尾(您可以跳过select命令,Format-Table也会获取属性列表(

Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties description | Format-Table -Property name,description -Wrap -AutoSize | Tee-Object -FilePath C:Group_List.txt

如果输出文件是供其他计算机/程序稍后使用的,我会更改策略并导出到CSV文件。为了捕获数据并将其输出到两者,我们可以将初始查询的结果分配给一个变量,然后在单独的语句中输出两次:

$groupsWithDescription = Get-ADPrincipalGroupMembership $username |Get-ADGroup -Properties description |Select-Object Name,Description
# Output to screen, format as table
$groupData |Format-Table -Wrap -AutoSize 
# Output to file, export data as CSV
$groupData |Export-Csv -Path C:Group_List.txt -NoTypeInformation

首先,您不在任何位置捕获Get-ADPrincipalGroupMembershipcmdlet的结果,只需使用Format-Table将其发送到屏幕。

其次,输出不会显示属于这些组的用户,因此,如果您正在键入另一个用户,则文件不会显示这些组对哪个用户有效。。

最后,插入一个测试来检查输入的用户名是否真的是现有用户。

我会输出一个CSV文件,你可以简单地在Excel中打开。类似这样的东西:

Import-Module activedirectory
$outFile  = 'C:Group_List.csv'
$username = Read-Host 'Please enter Username!'
# do some error checking to see if this is an existing user
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
$groups = Get-ADPrincipalGroupMembership -Identity $user.DistinguishedName | 
Get-ADGroup -Properties Description | ForEach-Object {
# output an object with properties you need
[PsCustomObject]@{
User        = $username
Group       = $_.Name
Description = $_.Description
}
}
# show on screen
$groups | Format-Table -Wrap -AutoSize
# write to CSV file
$groups | Export-Csv -Path $outFile -UseCulture -NoTypeInformation
$wsh = New-Object -ComObject Wscript.Shell
$wsh.Popup("List has been saved to $outFile")
# clean up COM object after use
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wsh)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
else {
Write-Warning "User $username does not exist.."
}
  1. 尝试在您的"获取ADPrincipalGroupMembership";。应该看起来像这样。

    获取ADPrincipalGroupMembership$username|获取ADGroup-属性*|选择名称、描述|格式化表-换行-AutoSize |输出文件-文件路径$path
  2. 使用导出csv

    `$result|export csv-路径$csvFileName-无类型信息`

最新更新