0

I have the following script, but I need to replace the Write-Host's and store the output in a single variable rather than writing the output.

I want to end up with all the output in one variable that I can then email the contents of.

Write-Host $machines2 at the end of the loop lists each machine to the console.

# 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 & 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 > 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, '(?<=StartDate>)(.*)(?=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;
        }
    }
}

1 Answer 1

3

Don't save your output to a variable, rather output in to the pipeline. Wrap your code into a function and collect whatever is returned, into a variable, similar to this:

function abc()
{
    $string1
    .... #processing block 1
    $string2
    .... #processing block 2
    $string3
    .... #even more processing.
}

If it is a set of strings, you can then join them together and send over the email:

$mydata = abc;
$myEmailBody = $mydata -join "`n";
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure how to apply this to the code above could you show me? I mean there are plenty of variables set in the above code but I only want $machines2 result from each record in the loop returning into the function
If you just want $machines2 in the output, replace that line with just "EXPIRED" + " " + $name + " " + $user2 + " " + $serial + " " + $tbr (remove $machines2 =).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.