title: PowerShell script to add output to a variable
body: <p>I have the following script, but I need to replace the <code>Write-Host</code>'s and store the output in a single variable rather than writing the output.</p>
  
  <p>I want to end up with all the output in one variable that I can then email the contents of.</p>
  
  <p><code>Write-Host $machines2</code> at the end of the loop lists each machine to the console.</p>
  
  <pre><code># Start writing headers to output
  write-host "        MACHINE  USER  TAG    EXPIRY DATE"
  
  # Import SQL module for PowerShell
  import-module SQLPS -DisableNameChecking
  
  # Run first SQLquery to get machine name &amp; servie tag
  $data1 = Invoke-Sqlcmd -ServerInstance SERVER -Database DATABASE -Query “SELECT guid, name, [Serial Number] FROM dbo.wrksta as a inner join Inv_AeX_HW_Serial_Number as b on a.GUID=b._resourceGUID ORDER BY Name”;
  
  # Iterate through results and apply logic to populate list
  foreach ($row in $data1)
  {
      # Set variables from Query result
      $name = $row.name;
      $serial = $row."Serial Number";
  
      # Get machine user
      $user = invoke-sqlcmd -ServerInstance SERVER -Database DATABASE -Query “SELECT top 1 [User] FROM dbo.Evt_aex_client_logon WHERE _resourceGuid = (SELECT top 1 Guid FROM dbo.Wrksta WHERE Name='$name' ORDER BY WrkstaID DESC) AND Event = 'logon' AND _eventTime &gt; getdate()-60 GROUP BY [User] ORDER BY count([User]) desc” ;
  
      # Set machine user without column header
      $user2 = $user.User;
  
      # Set service tag from query data
      [String]$ServiceTag = $serial;
  
      Try
      {
          # Function to obtain XML information about a Dell system from a service tag from the Dell xserv site
          $AssetService = New-WebServiceProxy -Uri "http://xserv.dell.com/services/AssetService.asmx?WSDL";
          $ApplicationName = "AssetService";
          $Guid = [Guid]::NewGuid();
          $Asset = $AssetService.GetAssetInformation($Guid, $ApplicationName, $ServiceTag);
          $Writer = New-Object "System.IO.StringWriter";
          $XmlSerializer = New-Object System.Xml.Serialization.XmlSerializer($Asset.GetType());
          $XmlSerializer.Serialize($Writer, $Asset);
          [String]$Date = $Writer.ToString();
          $Writer.Flush();
          $Writer.Close();
      }
      # Required exception block
      Catch
      {
          Write-Host $($_.Exception.Message);
      }
  
      # Match purchase date from returned data in incorrect format 2012-03-23
      $prog = [regex]::match($Date, '(?&lt;=StartDate&gt;)(.*)(?=T00)').Groups[1].Value
  
      # Edit the date to replace the - with /
      $prog2 = [System.Text.RegularExpressions.Regex]::Replace($prog, "[-]", "/");
  
      if ($prog2)
      {
          # Parse the value e.g. 2012/03/23 into a full datetime i.e. 23 March 2012 12:00:00
          $dt = [datetime]::ParseExact($prog2, "yyyy/MM/dd", $null)
  
          # Now string is in datetime format use the -format command to re-order and trim to our desired date 23/03/2012
          $purchased = Get-Date $dt -Format 'dd/MM/yyyy'
  
          # Store all variables in a table with relevant column headings
          $machines = New-Object PSObject -Property @{Name = $name; Serial = $Serial; User2 = $user2; purchased = $purchased}
  
          # Set what the date was 4 years ago today
          $fourYearsAgo = (Get-Date).AddYears(-4)
  
          # Compare our returned date to the date 4 years ago and see if it is less than or equal too i.e. in warranty
          $tobereplaced = $machines.purchased | Where-Object { (Get-Date $machines.purchased) -le $fourYearsAgo}
  
          if ($tobereplaced)
          {
              # Parse the date back to a full date/time
              $dt2 = [datetime]::ParseExact($tobereplaced, "dd/MM/yyyy", $null)
  
              # Add 4 years onto the date
              $replacementdate = (get-date $dt2).AddYears(+4)
  
              # Trim it back to our desired format
              $tbr = Get-Date $replacementdate -Format 'dd/MM/yyyy'
  
              # Build our final variable containing our data
              "EXPIRED" + " " + $name + " " + $user2 + " " + $serial + " " + $tbr;
          }
      }
  }
  </code></pre>