0

我有以下脚本,但我需要替换Write-Host's 并将输出存储在单个变量中,而不是编写输出。

我想在一个变量中结束所有输出,然后我可以通过电子邮件发送其内容。

Write-Host $machines2在循环结束时将每台机器列出到控制台。

# 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;
        }
    }
}
4

1 回答 1

3

不要将输出保存到变量中,而是输出到管道中。将您的代码包装到一个函数中,并将返回的任何内容收集到一个变量中,类似于以下内容:

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

如果它是一组字符串,您可以将它们连接在一起并通过电子邮件发送:

$mydata = abc;
$myEmailBody = $mydata -join "`n";
于 2012-10-23T15:56:20.227 回答