是否有任何脚本通过电子邮件登录用户信息

时间:2015-12-08 11:41:16

标签: powershell

大家好,我想知道是否有任何脚本会通过电子邮件通知用户信息,如用户名,计算机名,客户端IP,客户名,日期和时间等。

以下是我从technet获取的脚本,但它将计算机名称显示为本地主机,是否可以输出记录的文件和电子邮件作为附件?

Param(
    [CmdletBinding()] 
    [Parameter(ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true)]
    [string[]]$ComputerName = 'localhost'
)

Begin {
    $ErrorActionPreference = 'Stop'
}

Process {
    foreach ($Computer in $ComputerName) {
        try {
            quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
                $CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
                $HashProps = @{
                    UserName = $CurrentLine[0]
                    ComputerName = $Computer
                }

                # If session is disconnected different fields will be selected
                if ($CurrentLine[2] -eq 'Disc') {
                    $HashProps.SessionName = $null
                    $HashProps.Id = $CurrentLine[1]
                    $HashProps.State = $CurrentLine[2]
                    $HashProps.IdleTime = $CurrentLine[3]
                    $HashProps.LogonTime = $CurrentLine[4..6] -join ' '
                    $HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '
                } else {
                    $HashProps.SessionName = $CurrentLine[1]
                    $HashProps.Id = $CurrentLine[2]
                    $HashProps.State = $CurrentLine[3]
                    $HashProps.IdleTime = $CurrentLine[4]
                    $HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '
                }

                New-Object -TypeName PSCustomObject -Property $HashProps |
                Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
            }
        } catch {
            New-Object -TypeName PSCustomObject -Property @{
                ComputerName = $Computer
                Error = $_.Exception.Message
            } | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想脚本用法应该是:

  • 将其保存在.ps1文件
  • 使用-ComputerName 'hostname'参数调用它,允许您选择目标计算机

在这里,' localhost'是此参数的默认值。

要发送电子邮件,请检查Send-MailMessage cmdlet(需要PS 3.0)。

如果您需要将脚本作为计划任务运行,请设置Action字段,如下所示:

program = C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

arguments = -File "C:\path\to\script.ps1"