patelbg2001
asked on
Using data from a asp textbox as a query into a powershell script
Hi,
I'm am using this blog site as my reference for an initial start point -http://jeffmurr.com/blog/?p=142
I just needed some pointers. I'm creating an asp page, a c# script to execute, using the data presented in a text box, feeding this data into a powershell script.
I'm looking for advice into how that data can be presented to the powershell script to use in a foreach statement.
I'm am using this blog site as my reference for an initial start point -http://jeffmurr.com/blog/?p=142
I just needed some pointers. I'm creating an asp page, a c# script to execute, using the data presented in a text box, feeding this data into a powershell script.
I'm looking for advice into how that data can be presented to the powershell script to use in a foreach statement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExecuteCode_Click(object sender, EventArgs e)
{
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell Engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript("C:\\Scripts\\Reports\\CheckList.ps1");
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' characters like < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
}
}
}
ASKER
i was hoping to grab the email address & list from a textbox (multiline) and use a foreach etc... from the textbox and send the results back by email???? Thanks for the help, I'm learning both C# and aspx at the same time. So I appericate the help given.
Thanks
B.
My aspx page
My Powershell Script
Thanks
B.
My aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReportDemo.aspx.cs" Inherits="ReportDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="ReportStyleSheet.css">
</head>
<body>
<form id="form1" runat="server" draggable="false">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter Email Address: "></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="225px" style="margin-top: 0px" TextMode="Email">Email Address</asp:TextBox>
Enter SOIED List:
<br />
<asp:TextBox ID="TextBox2"
runat="server"
Height="183px"
Width="114px"
TextMode="MultiLine"
MaxLength="7">enternames</asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="ExecuteCode_Click" />
<br />
</div>
</form>
</body>
</html>
My Powershell Script
<#
#>
######### Script Timer Start ########
$StopWatch = New-Object System.Diagnostics.Stopwatch
$StopWatch.Start()
######### DATE VARIABLES ########
$Date = get-date -format R
$CurrentDir = Get-location
#### FORMAT TIMESTAMP TO APPEND REPORT FILENAMES WITH ########
$Timestamp = get-date -format g
$Timestamp = $Timestamp -replace(" ", "")
$Timestamp = $Timestamp -replace("/", "")
$Timestamp = $Timestamp -replace(":", "")
#### ADD POWERSHELL SNAPIN'S ########
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Support -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
##### TEMP OUTPUT FILES TO BE CREATED & REMOVED AT THE END OF THE SCRIPT ######
$csv = $CurrentDir.Path + "\mbxsizereport" + $Timestamp + ".csv"
##### EXPAND POWERSHELL TO VIEW ENTIRE FOREST######
Write-Verbose "Expanding PS to view the AD Forest"
Set-ADServerSettings -ViewEntireForest $true -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
Start-Sleep -s 10
Write-Host "Expanding Exchange to View Entire Forest" -Fore Green
##### REPORTING SCRIPT ARRAYS ######################
$results = New-Object System.Collections.ArrayList # Empty Array
$results = $NULL
$results = @()
##### IMPORT LIST FROM ASPX PAGE #############
##### HTML TABLE VARIABLES ################
$Bad = "Exchange 2007 Mailbox"
$Good = "Exchange 2010 Mailbox"
$BadArc = "No Archive Mailbox"
$BadStat = "Could Not Find Stats"
$PRM = "5120"
$STD = "2048"
##### HTML DATA ##################
Foreach($mbx1 in $_.) {
IF($mbx1 -ne $NULL) {
$Ismbx2k10 = Get-Mailbox -id $mbx1 | Select Name, ExchangeVersion, ArchiveDatabase, Database
$Object = New-Object PSObject
$A1 = $Ismbx2k10.Name
$A2 = $Ismbx2k10.ExchangeVersion.ExchangeBuild.Major
$A3 = [STRING] $Ismbx2k10.ArchiveDatabase
IF ($A1 -ne $NULL) {
$Object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $A1
}
IF($Ismbx2k10.ExchangeVersion.ExchangeBuild.Major -ne "14") {
$Object | Add-Member -Name 'Exchange Version' -MemberType Noteproperty -Value $BAD
} ELSE {
$Object | Add-Member -Name 'Exchange Version' -MemberType Noteproperty -Value $GOOD
}
IF($Ismbx2k10.ArchiveDatabase -eq $NULL) {
$Object | Add-Member -Name 'Archive Database' -MemberType Noteproperty -Value $BADARC
} ELSE {
$Object | Add-Member -Name 'Archive Database' -MemberType Noteproperty -Value $A3
}
$MBXStats = Get-Mailbox -id $mbx1 | Get-MailboxStatistics
$bytesize = ($MBXStats.TotalItemSize -replace "(.*\()|,| [a-z]*\)", "")
$DB = [STRING] $MBXStats.Database
$SizeInMb = ($bytesize / 1mb)
$SizeInGb = ($bytesize / 1gb)
$MB = [decimal]::round($SizeInMb)
$GB = [decimal]::round($SizeInGb)
IF ($DB -eq $NULL) {
$Object | Add-Member -Name 'Database Name' -MemberType Noteproperty -Value $BadStat
} ELSE {
$Object | Add-Member -Name 'Database Name' -MemberType Noteproperty -Value $DB
}
IF ($bytesize -eq $NULL) {
$Object | Add-Member -Name 'MbxSizeUsedinBytes' -MemberType Noteproperty -Value $BadStat
} ELSE {
$Object | Add-Member -Name 'MbxSizeUsedinBytes' -MemberType Noteproperty -Value $bytesize
}
IF ($bytesize -eq $NULL) {
$Object | Add-Member -Name 'MbxSizeUsedinMB' -MemberType Noteproperty -Value $BadStat
} ELSE {
$Object | Add-Member -Name 'MbxSizeUsedinMB' -MemberType Noteproperty -Value $MB
}
$formula1 = $PRM-$MB
$formula2 = $STD-$MB
IF ($MBXStats.DatabaseName -like "*PRM*") {
$Object | Add-Member -Name 'MbxSizeAvailableMB' -MemberType Noteproperty -Value $PRM
$Object | Add-Member -Name 'MbxSpaceAvailableMB' -MemberType Noteproperty -Value $Formula1
} ELSE {
$Object | Add-Member -Name 'MbxSizeAvailableMB' -MemberType Noteproperty -Value $STD
$Object | Add-Member -Name 'MbxSpaceAvailableMB' -MemberType Noteproperty -Value $Formula2
}
# Add-Content $HtmlReport "</tr>"
$results += $object
}
}
$results | export-csv $csv -notypeinformation
######### Script Timer End ########
# Finally, stop the stopwatch
$ElapsedTime = $StopWatch.Elapsed
# Write a line to the console with the results.
Write-Host "The script took" $ElapsedTime.Hours "hours," `
$ElapsedTime.Minutes "minutes, and" $ElapsedTime.Seconds "seconds to run."
######### Script Timer End ########
# EMAIL MESSAGE BODY
#
$body = "Mailbox Report.`n`n"
$body = $body + "MailboxReport : " + $csv + "`n`n"
}
#
# TRANSMIT EMAIL
#
$CurrentDate = get-date -uformat "%m-%d-%Y"
[String[]] $To = "User@abc.com"
#
[String] $Subject = "Mailbox Report - $CurrentDate"
[String] $SMTPHost = "mail.mx.local"
[String] $From = "bp@mx.local"
#
$email = New-Object System.Net.Mail.MailMessage
$attachment = New-Object System.Net.Mail.Attachment $csv
foreach($mailTo in $to) {$email.To.Add($mailTo)}
$email.Subject = $subject
$email.attachments.add($attachment)
$email.Body = $body
$email.From = $From
#
$client = New-Object System.Net.Mail.SmtpClient $smtpHost
$client.UseDefaultCredentials = $true
$client.Send($email)
#
Scraping email addresses and "list?" from a multi-line free form textbox is error prone and not a good idea. I'd recommend using a repeater instead and ask for what you want.
ASKER
Steve, what is a repeater? (Yes the multiline text box idea, looks flawed for the reason of maxcharcters per row, is an issue as it only works in single line text boxes).
Here's an example:
http://www.aspnettutorials.com/tutorials/controls/Repeater-Csharp/
This was obtained with an Internet search using keywords:
aspx repeater c# example
http://www.aspnettutorials.com/tutorials/controls/Repeater-Csharp/
This was obtained with an Internet search using keywords:
aspx repeater c# example
ASKER
A repeater is not what I am looking for. I would like the data to be entered into a text box, which can be fed into the script.
My alternate option is to have the data imported and scooped up by a script and then actioned (if possible I would prefer the list entered via a multiline text box, if it can be limited to 7 characters per line)?
My alternate option is to have the data imported and scooped up by a script and then actioned (if possible I would prefer the list entered via a multiline text box, if it can be limited to 7 characters per line)?
The repeater would be used to enter multiple distinct emails. In any case that is really a question for another forum.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, that would have worked, makes sense to add a splitter to the submission.
Open in new window
This would be accomplished by adding the parameters to the C# call:
Open in new window
Sounds like you are wanting to process an array. You could define the specific parameter to the script by using the param keyword at the top of your script and then you could process it using a foreach command:
Open in new window
You'd call this in your code like so:
Open in new window