简体   繁体   English

Powershell,我输入一个列表收集数据和 output 整个列表到一个 CSV

[英]Powershell, I do input a list gather data and output that whole list into one CSV

I am creating a script that reads a list of computer names and collects data from security event logs about who is on the computer, how long they have been on for, and how long it has been since the computer has restarted.我正在创建一个脚本,它读取计算机名称列表并从安全事件日志中收集有关谁在计算机上、他们已经打开了多长时间以及计算机重新启动以来已经过了多长时间的数据。 I have it working except that it does not output all the data into one CSV.我让它工作,除了它没有 output 将所有数据放入一个 CSV。 I just receive one CSV file with one computer name.我只收到一个带有一台计算机名称的 CSV 文件。

function Get-KioskInfo {

    param (

        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=0)]
        [Alias('PSComputerName','DNSHostName','CN','Hostname')]

        [string]
        $ComputerName = $env:COMPUTERNAME
        )
        #PARAM
        $User = try {(Get-WmiObject -ComputerName $ComputerName Win32_ComputerSystem | Select-Object -ExpandProperty username).trimstart("NG\")} catch {Write-Output "User not detected";break}
        $BootStart = ((get-date) - (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).LastBootUpTime).Days
        
        #These variables are for the DATE & Time calculation
        If ($user -NE $null) 
            { Write-Verbose 1
            # Do something
            $Date1 = Get-date
            Write-Verbose 2
            $SP = Get-WinEvent -ComputerName $ComputerName -FilterHashTable @{LogName = "Security";ID="5379";Data=$User; StartTime=((Get-Date).AddDays(-1))}
            Write-Verbose 3
            $Date2 =($SP | select -first 1).timecreated
            Write-Verbose 4
            $USERLOGTIME = ($Date1-$Date2).hours.tostring("N2")
            Write-Verbose 5
            }
        else{Write-Output "No user";break}
        Write-Verbose 6



        #Rename-Computer -ComputerName "Srv01" -NewName "Server001" -DomainCredential Domain01\Admin01 -Force ------ Rename script for computers if it is needed.
        #$computers = Get-Content C:\Users\jaycbee\Desktop\kiosknames.txt ------ To load kiosk list
        #foreach ($c in $computers) {start-job -Name $c -ScriptBlock ${Function:get-kioskinfo} -ArgumentList $c} for learning how to do a foreach script
        


Write "Computer Name: $Computername"
Write "---USER---"
Write "Name:          $User"
Write "Log in Time    $USERLOGTIME"
Write "Boot start     $BootStart days ago"

$ComputerName | ForEach-Object   {

    if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet)
        {

        Invoke-Command -ComputerName $ComputerName {




}      

  } # Offline Check

    else 
        { 
            Write-Host "Computer is Unreachable or Offline" -ForegroundColor Gray 
        }    


} # Foreach

$Continue = Read-Host "WARNING! This will READ LIST of computers in \\ou\ouor-groups\Desktop_Support\SD\Kiosks\kiosknames.txt Type CONTINUE to proceed."
if ($Continue -eq "CONTINUE")
  {
        $Computers = Get-Content '\\ou\ouor-groups\Desktop Support\SD\Kiosks\kiosknames.txt'
        foreach ($C in $Computers) {start-job -Name $c -ScriptBlock ${Function:get-kioskinfo} -ArgumentList $c
        }
        }

[pscustomobject]@{ Name = $ComputerName ; User = $User ; "User Log in time in hours" = $USERLOGTIME;"BootStart days ago" = $BootStart} | export-csv -path "\\ou\ouor-groups\Desktop Support\SD\Kiosks\test45$ComputerName.csv" -Append

} #Function

#For each-computer | do this at this location, 

Continuing from my comment.继续我的评论。 I too wonder why the use of jobs for this use case.我也想知道为什么在这个用例中使用作业。 Unless you are doing this on hundreds of computers, thus needing parallel processing.除非您在数百台计算机上执行此操作,否则需要并行处理。

This refactor/formatting is just my way of making sense of what you posted.这种重构/格式化只是我理解您发布的内容的方式。 I'm old, and crowded code just really hurts my eyes.我老了,拥挤的代码真的伤了我的眼睛。 ;-} Yet, code the way you like of course. ;-}然而,当然,以你喜欢的方式编码。 ;-} ;-}

I do not have an environment to test this, but give it a shot.我没有测试这个的环境,但试一试。

function Get-KioskInfo 
{
    param 
    (
        [parameter(ValueFromPipeline = $True,ValueFromPipelineByPropertyName = $True,Position = 0)]

        [Alias(
            'PSComputerName',
            'DNSHostName',
            'CN',
            'Hostname'
        )]
    
        [string]
        $ComputerName = $env:COMPUTERNAME
    )

    ($User = try 
             {
                (Get-WmiObject -ComputerName $ComputerName Win32_ComputerSystem | 
                Select-Object -ExpandProperty username).trimstart("NG\")
             } 
             catch 
             {
                 'User not detected'
                 break
             }
    )

    ($BootStart = ((get-date) - (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).LastBootUpTime).Days)
    
    If ($user -NE $null) 
    { 
        ($Date1  = Get-date)
        ($SP     = Get-WinEvent -ComputerName $ComputerName -FilterHashTable @{
                                                            LogName   = 'Security'
                                                            ID        = '5379'
                                                            Data      = $User
                                                            StartTime = ((Get-Date).AddDays(-1))
                                                        })

        ($Date2 = (
                    $SP | 
                    select -first 1
                 ).timecreated)

        ($USERLOGTIME = ($Date1-$Date2).hours.tostring('N2'))
    }
    else
    {
        'No user'
        break
    }

    "Computer Name: $Computername
    ---USER---
    Name:          $User
    Log in Time    $USERLOGTIME
    Boot start     $BootStart days ago"

    $ComputerName | 
    ForEach-Object {
        if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet)
        {Invoke-Command -ComputerName $ComputerName}
        else 
        {Write-Warning -Message 'Computer is Unreachable or Offline'}    
    } 

    $UserMessage = '
    WARNING!
        This will READ LIST of computers in: 
        \\ou\ouor-groups\Desktop_Support\SD\Kiosks\kiosknames.txt 
    Type CONTINUE to proceed'
    $Continue = Read-Host $UserMessage 

    if ($Continue -eq 'CONTINUE')
    {
        Get-Content '\\ou\ouor-groups\Desktop Support\SD\Kiosks\kiosknames.txt' | 
        foreach {
            {start-job -Name $PSItem -ScriptBlock ${Function:get-kioskinfo} -ArgumentList $PSItem}

            [pscustomobject]@{ 
                                Name                        = $ComputerName
                                User                        = $User
                                'User Log in time in hours' = $USERLOGTIME
                                'BootStart days ago'        = $BootStart
                             } 
        } | 
        Export-Csv -path "$PWD\$ComputerName.csv" -Append 
    } 
}

These didn't help me with my solution, but you were right about the start-jobs.这些对我的解决方案没有帮助,但你对开始工作的看法是对的。 I have to rework the entire script in order to get the correct info.我必须重新编写整个脚本才能获得正确的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM