Solved

Using data from a asp textbox as a query into a powershell script

Posted on 2014-04-16
9
1,063 Views
Last Modified: 2014-04-21
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.

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());
				}
			}
		}
	}

Open in new window

0
Comment
Question by:patelbg2001
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 30

Expert Comment

by:SteveGTR
ID: 40004590
The Powershell script could reference the parameters in a number of ways. The simplest would be through the $args variable:

if ($args)
{
	$args
}
else
{
	"Nothing"
}

Open in new window


This would be accomplished by adding the parameters to the C# call:

shell.Commands.AddScript("C:\\Scripts\\Reports\\CheckList.ps1 Test");

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:

param
(
    [int[]] $num
)

foreach ($n in $num)
{
    $n
}

Open in new window


You'd call this in your code like so:

shell.Commands.AddScript("C:\\Scripts\\Reports\\CheckList.ps1 1,2,3");

Open in new window

0
 
LVL 6

Author Comment

by:patelbg2001
ID: 40011418
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

<%@ 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>
        &nbsp;
        <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>

Open in new window


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)
#

Open in new window

0
 
LVL 30

Expert Comment

by:SteveGTR
ID: 40011433
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.
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 6

Author Comment

by:patelbg2001
ID: 40011445
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).
0
 
LVL 30

Expert Comment

by:SteveGTR
ID: 40011448
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
0
 
LVL 6

Author Comment

by:patelbg2001
ID: 40011558
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)?
0
 
LVL 30

Expert Comment

by:SteveGTR
ID: 40011767
The repeater would be used to enter multiple distinct emails. In any case that is really a question for another forum.
0
 
LVL 30

Accepted Solution

by:
SteveGTR earned 500 total points
ID: 40011789
If you required the emails addresses to be separated with a semi-colon in the multi-line edit box, you could pass them to your p0wershell script and process them like this:

# $args example: s1@test.com;s2@test.com;s31@test.com;

foreach ($e in $args.split(";"))
{
    $e
}

Open in new window

0
 
LVL 6

Author Comment

by:patelbg2001
ID: 40012447
Thanks, that would have worked, makes sense to add a splitter to the submission.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Previously, on our Nano Server Deployment series, we've created a new nano server image and deployed it on a physical server in part 2. Now we will go through configuration.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question