Как прочитать входные данные через CSV-файл и записать вывод в выходной файл в сценарии Power Shell? - PullRequest
0 голосов
/ 15 апреля 2020

Sharing the screenshot of input csv file [Sharing the screenshot of input csv file] Это сценарий powershell для получения статуса выбранных сервисов серверов, где список серверов передается через входной файл csv и статус этих серверов должен храниться в выходной файл.

----------- Ниже приведен скрипт ----------

$Servers = Get-Content "C:\temp\input.csv"
$Log = @()
foreach($Server in $Servers)
{
    $Services = Get-Service *HRRA*, "SQL Server Reporting Services" -ComputerName $COMPUTERNAME
    foreach ($Service in $Services)
    {
    $properties = @(
                  @{n='ServiceName';e={$Service.Name}}
                  @{n='Status';e={$Service.Status}}
                  @{n='ServerName';e={$Server}}
                  )
    $Log += "" | select $properties
    }

}
$Log  | Format-Table -AutoSize | Out-File "D:\temp\test.txt" -Force

------ ------------------------------ Новый скрипт ------------------ ----------------

$Computers = Import-Csv "C:\Temp\Input.csv"
#$mailboxdata =  Get-Service *HRRA*,"SQL Server Reporting Services" -ComputerName $ComputerName| select machinename,name, status | sort machinename | 
#format-table -AutoSize |Out-File "D:\Temp\RRR.txt"
#LogWrite "$ComputerName"
foreach($row in $computers)
{
{
Add-Content -Path D:\Temp\SSRS.txt -Value $mailboxdata }
Get-Content -Path D:\Temp\SSRS.txt  
                 $ComputerName= $row.ComputerName;
$mailboxdata =  Get-Service *HRRA*,"SQL Server Reporting Services" -ComputerName $ComputerName| select machinename,name, status | sort machinename | 
format-table -AutoSize |Out-File "D:\Temp\SSR.txt"
$fromaddress = "Reporting.Services@accenture.com" 
$toaddress = "aditi.m.singh@accenture.Com"
#$toaddress1 = "s.ab.balakrishnan@accenture.com"
$Subject = "SSRS Services Status" 
$body = "Please find attached - test"
$attachment = "D:\Temp\SSR.txt" 
$smtpserver = "AMRINT.SMTP.ACCENTURE.COM"
$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress)
#$message.To.Add($toaddress1)
$message.IsBodyHtml = $True 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$smtp.Send($message)

}

If i am running the script with static value its giving me output for both the servers---Below is the script----
Get-Service *HRRA*,"SQL Server Reporting Services" -ComputerName VW118627, VW118623 | select name, status, machinename | sort machinename | format-table -AutoSize |
Out-File "D:\Temp\Report.txt"

This is the output i am getting after giving server name as static values

1 Ответ

0 голосов
/ 15 апреля 2020

Глядя на скриншот, я вижу, что входной CSV - это действительно C omma S выделенный V файл с данными. Для этого вы используете командлет Import-Csv для извлечения массива имен компьютеров из файла.

$outputFile = "D:\temp\test.csv"

# make sure the field name matches what is in the CSV header
$Servers = (Import-Csv -Path "C:\temp\input.csv").ComputerName  

$Log = foreach($Server in $Servers) {
    # add a test to see if we can reach the server
    if (Test-Connection -ComputerName $Server -Count 1 -Quiet -ErrorAction SilentlyContinue) {
        Get-Service -Name *HRRA*, "SQL Server Reporting Services" -ComputerName $Server | 
        Select-Object @{Name = 'MachineName'; Expression = {$Server}},
                      @{Name = 'ServiceName'; Expression = {$_.Name}},
                      @{Name = 'Status';      Expression = {$_.Status}}
    }
    else {
        Write-Warning "Server '$Server' is unreachable"
    }
}

# if you want the log sorted, do
$Log = $Log | Sort-Object MachineName

# output on screen
$Log | Format-Table -AutoSize 

# output to CSV file
$Log | Export-Csv -Path $outputFile -Force -NoTypeInformation

# mail the output csv file using Send-MailMessage
# collect the parameters in a hashtable
$mailParams = @{
    SmtpServer  = "AMRINT.SMTP.ACCENTURE.COM"
    From        = "Reporting.Services@accenture.com"
    To          = "aditi.m.singh@accenture.com"
    Subject     = "SSRS Services Status"
    Body        = "Please find attached - test"
    BodyAsHtml  = $true
    Attachments = $outputFile
    # add other parameters if needed
    # see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage
} 
# use 'splatting' to send the email 
# see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting
Send-MailMessage @mailParams

PS Командлет Format-Table предназначен для отображения объектов (объектов) только на экране .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...