在循环中导出每个变量值

时间:2017-07-06 20:10:06

标签: powershell powershell-v3.0

每次参数经过foreach循环时,我都会尝试捕获变化的变量'$ server'。总而言之,$ sever值总是在变化,我想捕获它并将其添加到集体csv文件中

谢谢!

以下是我所拥有的代码的主要部分。

 function Convert-QueryToObjects
 {
   [CmdletBinding()]
   [Alias('QueryToObject')]
   [OutputType([PSCustomObject])]
   param
   (
    [Parameter(Mandatory = $false,
               ValueFromPipeline = $true,
               ValueFromPipelineByPropertyName = $true,
               Position = 0)]
    [Alias('ComputerName', 'Computer')]
    [string]
    $Name = $env:COMPUTERNAME
)

Process
{
    Write-Verbose "Running query.exe against $Name."
    $Users = query user /server:$Name 2>&1

    if ($Users -like "*No User exists*")
    {
        # Handle no user's found returned from query.
        # Returned: 'No User exists for *'
        Write-Error "There were no users found on $Name : $Users"
        Write-Verbose "There were no users found on $Name."
    }
    elseif ($Users -like "*Error*")
    {
        # Handle errored returned by query.
        # Returned: 'Error ...<message>...'
        Write-Error "There was an error running query against $Name : $Users"
        Write-Verbose "There was an error running query against $Name."
    }
    elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
    {
        # Handdle null output called by -ErrorAction.
        Write-Verbose "Error action has supressed output from query.exe. Results were null."
    }
    else
    {
        Write-Verbose "Users found on $Name. Converting output from text."

        # Conversion logic. Handles the fact that the sessionname column may be populated or not.
        $Users = $Users | ForEach-Object {
            (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
        } | ConvertFrom-Csv

        Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

        # Output objects.
        foreach ($User in $Users)
        {
            Write-Verbose $User
            if ($VerbosePreference -eq 'Continue')
            {
                # Add '| Out-Host' if -Verbose is tripped.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                } | Out-Host
            }
            else
            {
                # Standard output.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                }
            }
        }
    }
}
}








$Servers = Get-Content 'H:\demo\computernames.txt'

foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }

if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {



      $server | Out-File 'H:\demo\session\run1.csv' -Append 


    }
else
{
   Convert-QueryToObjects -Name $Server | select ComputerName, Username, Sessionstate, IdleTime, ID | Export-Csv 'H:\demo\session\run.csv' -NoTypeInformation
}
}

2 个答案:

答案 0 :(得分:0)

在foreach循环之外创建一个数组,并在foreach期间将$ server变量值添加到数组中。最后将数组导出到csv。

答案 1 :(得分:0)

未经测试,但您想要做这样的事吗?

Get-Content "H:\demo\computernames.txt" | ForEach-Object {
  $computerName = $_
  if ( Test-Connection $computerName -Count 1 -Quiet ) {
    Convert-QueryToObjects $computerName -ErrorAction SilentlyContinue
  }
  else {
    "$_ not pingable" | Out-File "H:\demo\session\notpingable.log" -Append
  }
} | Export-Csv "H:\demo\session\run.csv" -NoTypeInformation