Mi script sobrescribe la entrada anterior después de cada bucle "foreach"

Mi script sobrescribe la entrada anterior después de cada bucle "foreach"

El guión que tengo aquí escribe la información que quiero. Sin embargo, he notado que cada nueva entrada válida reemplaza a la última. No puedo entender por qué. Entonces, termino con solo 1 entrada cada vez, incluso si se detectaron 1000 computadoras. Por favor ayúdenme a resolver esto.

$computers = Get-ADComputer -SearchBase "DC=some,DC=web,DC=com" -Filter * | Select-Object -ExpandProperty Name
      foreach ($computer in $computers){
if(!(Test-Connection -CN $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
     {write-host "Cannot reach $computer offline." -f red}
      else {
$outtbl = @()
Try{
$sr=Get-WmiObject -Class Win32_BIOS -ComputerName $computer  -ErrorAction Continue 
$Xr=Get-WmiObject -Class Win32_Processor -ComputerName $computer -ErrorAction Continue   
$ld=Get-ADComputer $computer -Properties * -ErrorAction Continue
$r="{0} GB" -f ((Get-WmiObject Win32_PhysicalMemory -ComputerName $computer |Measure-Object Capacity  -Sum).Sum / 1GB)
$x = gwmi win32_computersystem -ComputerName $computer |select @{Name = "Type";Expression = {if (($_.pcsystemtype -eq '2')  ) 

{'Laptop'} Else {'Desktop Or Other something else.'}}},Manufacturer,@{Name = "Model";Expression = {if (($_.model -eq "$null")  ) {'Virtual'} Else {$_.model}}},username -ErrorAction Continue
$t= New-Object PSObject -Property @{
    ServiceTag = $sr.serialnumber
    ComputerName = $ld.name
    IPV4Address=$ld.ipv4Address
    Enabled=$ld.Enabled
    Description=$ld.description
    OU=$ld.DistinguishedName.split(',')[1].split('=')[1] 
    Type = $x.type
    Manufacturer=$x.Manufacturer
    Model=$x.Model
    RAM=$R
    ProcessorName=($xr.name | Out-String).Trim()
    NumberOfCores=($xr.NumberOfCores | Out-String).Trim()
    NumberOfLogicalProcessors=($xr.NumberOfLogicalProcessors | Out-String).Trim()
    AddressWidth=($xr.Addresswidth | Out-String).Trim()
    OperatingSystem=$ld.operatingsystem
    OperatingSystemServicePack=$ld.OperatingSystemServicePack
    OperatingSystemVersion=$ld.OperatingSystemVersion
    OperatingSystemHotfix=$ld.OperatingSystemHotfix
    LastLogonDate=$ld.lastlogondate
    ObjectCreated=$ld.Created
    ObjectModified=$ld.whenChanged
    LoggedInUser=$x.username
    }
    $outtbl += $t
    }
    catch [Exception]
    {
        "Error communicating with $computer, skipping to next"
    }
   $outtbl | select Computername,ServiceTag,IPV4Address,Description,Enabled,OU,Type,Manufacturer,Model,RAM,ProcessorName,NumberOfCores,NumberOfLogicalProcessors,AddressWidth,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion,OperatingSystemHotfix,ObjectCreated,ObjectModified,LoggedInUser,LastLogonDate | Format-Table * -Wrap -AutoSize | Out-String -Width 4096 | Out-File $env:USERPROFILE\Desktop\AD-Inventory.txt
}
}

Respuesta1

Su problema fue que el archivo se sobrescribió en cada bucle. ahora su secuencia de comandos primero guardará todo en una variable y luego lo exportará al final.

Algunos problemas más con tu script:

  • try/catch nunca detectará nada en este momento, porque no hay ningún error de terminación.
  • el formato de su guión era horrible; formatéelo mejor; de lo contrario, será muy difícil de leer.
  • ¿Por qué seleccionas todo al final antes de exportarlo? Si desea exportar todo, no necesita seleccionar cosas. si es para fines de clasificación, cámbielo New-Object PSObject -propertya [pscustomobject], esto ya forzará el orden de clasificación correcto

aquí está el script actualizado

$computers = Get-ADComputer -SearchBase "DC=some,DC=web,DC=com" -Filter * | Select-Object -ExpandProperty Name
$outtbl = foreach ($computer in $computers){
    if(!(Test-Connection -CN $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    { 
        write-host "Cannot reach $computer offline." -f red 
    }
    else {
        Try{
            $sr = Get-WmiObject -Class Win32_BIOS -ComputerName $computer  -ErrorAction Continue 
            $Xr = Get-WmiObject -Class Win32_Processor -ComputerName $computer -ErrorAction Continue   
            $ld = Get-ADComputer $computer -Properties * -ErrorAction Continue
            $r  = "{0} GB" -f ((Get-WmiObject Win32_PhysicalMemory -ComputerName $computer | Measure-Object Capacity  -Sum).Sum / 1GB)
            $x  = gwmi win32_computersystem -ComputerName $computer | select @{Name = "Type";Expression = {if (($_.pcsystemtype -eq '2')  ) 
                  {'Laptop'} Else {'Desktop Or Other something else.'}}},Manufacturer,@{Name = "Model";Expression = {if (($_.model -eq "$null")  ) {'Virtual'} Else {$_.model}}},username -ErrorAction Continue
            New-Object PSObject -Property @{
                ServiceTag = $sr.serialnumber
                ComputerName = $ld.name
                IPV4Address=$ld.ipv4Address
                Enabled=$ld.Enabled
                Description=$ld.description
                OU=$ld.DistinguishedName.split(',')[1].split('=')[1] 
                Type = $x.type
                Manufacturer=$x.Manufacturer
                Model=$x.Model
                RAM=$R
                ProcessorName=($xr.name | Out-String).Trim()
                NumberOfCores=($xr.NumberOfCores | Out-String).Trim()
                NumberOfLogicalProcessors=($xr.NumberOfLogicalProcessors | Out-String).Trim()
                AddressWidth=($xr.Addresswidth | Out-String).Trim()
                OperatingSystem=$ld.operatingsystem
                OperatingSystemServicePack=$ld.OperatingSystemServicePack
                OperatingSystemVersion=$ld.OperatingSystemVersion
                OperatingSystemHotfix=$ld.OperatingSystemHotfix
                LastLogonDate=$ld.lastlogondate
                ObjectCreated=$ld.Created
                ObjectModified=$ld.whenChanged
                LoggedInUser=$x.username
            }
        }
        catch [Exception]
        {
            "Error communicating with $computer, skipping to next"
        }
    }
}

$outtbl | select Computername,ServiceTag,IPV4Address,Description,Enabled,OU,Type,Manufacturer,Model,RAM,ProcessorName,NumberOfCores,NumberOfLogicalProcessors,AddressWidth,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion,OperatingSystemHotfix,ObjectCreated,ObjectModified,LoggedInUser,LastLogonDate | Format-Table * -Wrap -AutoSize | Out-String -Width 4096 | Out-File $env:USERPROFILE\Desktop\AD-Inventory.txt

información relacionada