Communication between website and windows - windows

This is general question, how to approach this problem.
For my technical degree i would like to do sort of website application that will connect windows machine, send a request to powershell e.g. get-processes, and in the end display it on the website.
I'm not sure if PowerShell Web Access can be modified like that, Is there any other solution?
Like service that i could communicate on?
-mateusz

You can use Powershell runspaces, this is an example, but in your case you might have to change it for the authentication methods in you have to use...
PSCredential credential = new PSCredential(user, secure_pw);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Credssp;
connectionInfo.ProxyAuthentication = AuthenticationMechanism.Negotiate;
connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
connectionInfo.OpenTimeout = 1 * 60 * 1000; // 1 minute.
connectionInfo.Credential = credential;
Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo);
rs.Open();
using (PowerShell PowerShellInstance = PowerShell.Create())
{
string hostname = "my-host";
PowerShellInstance.Runspace = rs;
PowerShellInstance.AddScript(string.Format("param([string]$hostname) Get-Process -ComputerName $hostname"))
PowerShellInstance.AddParameter("hostname", hostname);
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
// do something with the errors found.
if (PowerShellInstance.Streams.Error.Count > 0)
{
foreach (var error in PowerShellInstance.Streams.Error)
{
Console.WriteLine(error.Exception.Message);
}
}
}
rs.Dispose();
If do it this way, I recommend you do a bit of research about PowerShellInstance.AddScript vs PowerShellInstance.AddCommand and how the parameters have to be handled, etc...

Related

System.outofmemory exception when running Powershell script

I've written VC++ code to run Powershell scripts on a remote server. I create a PSSession to a server first and then I run around 30000 commandlets. While performing this operation, I receive System.outofmemory exception. I've also tried to increase 'MaxMemoryPerShellMB' to 2048, but that doesn't solve the problem. Kindly advise. This is my code:
runSpace = RunspaceFactory::CreateRunspace();
runSpace->Open();
ps = PowerShell::Create();
ps->Runspace = runSpace;
PSCommand^ rmcommand = gcnew PSCommand();
Uri^ uri = gcnew Uri("http://"+ serverName +"/powershell?serializationLevel=Full");
rmcommand->AddCommand("New-PSSession");
rmcommand->AddParameter("ConfigurationName", "Microsoft.Exchange");
rmcommand->AddParameter("ConnectionUri", uri);
rmcommand->AddParameter("Authentication", "kerberos");
rmcommand->AddParameter("Name", "pssession");
PSSessionOption^ sessionOption = gcnew PSSessionOption();
sessionOption->SkipCACheck = true;
sessionOption->SkipCNCheck = true;
sessionOption->SkipRevocationCheck = true;
rmcommand->AddParameter("SessionOption", sessionOption);
ps->Commands = rmcommand;
Collection<PSObject^>^ result = ps->Invoke();
rmcommand = gcnew PSCommand();
rmcommand->AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned");
ps->Commands = rmcommand;
ps->Invoke();
rmcommand = gcnew PSCommand();
rmcommand->AddScript("Import-PSSession -Session $session -CommandName 'Get-MailboxStatistics'");
ps->Commands = rmcommand;
ps->Invoke();
PSCommand^ command = gcnew PSCommand();
for(size i = 0; i < 30000; i++)
{
mbxidentity=mailbox[i];
command = gcnew PSCommand();
command->AddScript("Get-MailboxStatistics -Identity \'" + mbxidentity + "\' | select LegacyDN");
ps->Commands = command;
Collection<PSObject^>^ result = ps->Invoke();
//Do something with result
}
Here 'mailbox' is an array containing list of mailbox identities. Also, I get Outofmemory at different places. Sometimes I get it when running New-PSSession itself. Sometimes, around 1000 commandlets run successfully and then I get the exception. What might be the problem? I have checked the memory of the remote serve and it is fine.
I'm not very experienced with running powershell code with c++/c#. My comments were getting big, so I'll use an answer to ask questions etc.
Have you restarted the winrm-service on the server(s) after raising
the MaxMemoryPerShellMB?
Why are you running Get-Mailbox? I can't see that you're storing the output anywhere, and this would probably create a lot of objects = memory-usage

uninstalling applications using SCCM SDK

I have been trying to uninstall applications on devices or users using SCCM. I have been successful in creating an application assignment that would install applications, but I haven't been able to get it to uninstall. The code I have been using is:
IResultObject assignment = this.manager.CreateInstance("SMS_ApplicationAssignment");
IResultObject application =
this.manager.GetInstance("SMS_Application.CI_ID=16777339");
assignment["ApplicationName"].StringValue = application["LocalizedDisplayName"].StringValue;
assignment["AssignedCI_UniqueID"].StringValue = application["CI_UniqueID"].StringValue;
assignment["AssignedCIs"].IntegerArrayValue = new[] { application["CI_ID"].IntegerValue};
assignment["AssignmentName"].StringValue = "Deepak's deployment";
assignment["CollectionName"].StringValue = "Deepak's Collection of Devices";
assignment["DisableMomAlerts"].BooleanValue = true;
assignment["NotifyUser"].BooleanValue = false;
assignment["OfferFlags"].IntegerValue = 0;
assignment["DesiredConfigType"].IntegerValue = 1;
assignment["OverrideServiceWindows"].BooleanValue = false;
assignment["RebootOutsideOfServiceWindows"].BooleanValue = false;
assignment["SuppressReboot"].IntegerValue = 0;
assignment["TargetCollectionID"].StringValue = "UKN0000F";
assignment["EnforcementDeadline"].DateTimeValue = DateTime.Now.AddDays(1);
assignment["StartTime"].DateTimeValue = DateTime.Now;
assignment["UseGMTTimes"].BooleanValue = false;
assignment["UserUIExperience"].BooleanValue = false;
assignment["WoLEnabled"].BooleanValue = false;
assignment["RequireApproval"].BooleanValue = true;
assignment["OfferTypeId"].IntegerValue = 2;
assignment.Put();
This code will put up the application as an install deployment in SCCM. How do I get it as an uninstall deployment?
There is an AppAction enumeration, which I suspect is used by the client and not on the server.
typedef enum AppAction
{
appDiscovery = 0,
appInstall = 1,
appUninstall = 2
} AppAction;
Any help would be appreciated!
The setting that needs to be changed is DesiredConfigType.
For your code add the following before put():
assignment["DesiredConfigType"].IntegerValue = 2;
A value of 1 represents install (required) and 2 will uninstall (not allowed).
https://msdn.microsoft.com/en-us/library/hh949014.aspx
The way I do it is first use uninstall.exe to determine the guid of the program, and then create a program for the package I wish to uninstall, and just call uninstall.exe /whatever as the command. This works for most apps that show up in Add/Remove, and if it doesn't show up there then it'll have to be a hack (or script) anyway to uninstall. I believe the reason you're falling short is because if there is no command to uninstall the deployment in sccm, then it has nothing to run.
After you create an uninstall program, you could just call that deployment from your code, and voila.
As long as the target program that you are trying to use was installed via an MSI (Microsoft Installer) then you can loop through the registry to find your product (Registry Location: "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall") And just look at each DisplayName value.
In our environment, I accomplish this task by using Powershell, and we setup a program that specifically uninstalls whatever we are after.
Hope this helps...
Raged.

How to find out Joomla JTable column/field names?

I'm using Joomla 2.5 to build a medium-sized website, and I've decided to ease maintenance and content management headaches through creating menus automatically.
I've looked for extensions which did this, but only found Joomla 1.5 extensions. I ended up trying to upgrade a GPL extension called Auto Menu Magic.
It was easy to deal with the basic issues like the XML tags in the extension file, since there's a page in the Joomla which helps you migrate from Joomla 1.5 to 1.6.
The extension I mentioned has a function named onContentAfterSave which is called by joomla when an article is saved. I've been debugging through creating rubbish articles in the admin interface and changing the code to throw exceptions in several places, which I can see as error messages on the admin frontend.
This is where I got stuck:
$db = &JFactory::getDBO();
$menu = JTable::getInstance( 'menu');
$menu->menutype = $menutype;
$menu->name = $name;
$menu->link = $link;
$menu->type = $linktype;
$menu->published = $published;
$menu->componentid = $componentid;
$menu->parent = $menuparentid;
$menu->sublevel = $menusublevel;
$menu->checked_out = 0;
$menu->checked_out_time = 0;
$menu->pollid = 0;
$menu->browserNav = 0;
$menu->access = 0;
$menu->utaccess = 0;
$menu->lft = 0;
$menu->rgt = 0;
$menu->home = 0;
$menu->params = $params;
// Figure out the order (Just pop this article at the end of the list):
$menu->ordering = $menu->getNextOrder(
"menutype = ".$db->Quote($menu->menutype).
" AND published >= 0 AND parent = ".(int) $menu->parent
);
// Validate:
if (!$menu->check())
return NULL;
// DEBUG 2 -- Integrity check
throw new Exception ("menutype: $menutype, name: $name, link: $link published: $published, componentid: $componentid menuparentid: $menuparentid menusublevel: $menusublevel");
// Save:
if (!$menu->store())
return NULL;
// DEBUG 1
throw new Exception(" Could save! ");
As you can see above, I tried to throw an exception (DEBUG 1) when the menu was saved to the database. This exception was never reached, but the upper exception (DEBUG 2) is reached. This means that $menu->check() returns true, but not $menu->store(). I assume that the database is returning an error because some of the Joomla database structure might have changed after 1.5.
I have read the source a lot these past hours, but I can't find one thing. How can I look at the columns that a Joomla table uses, so I can debug this error properly?
Thanks in advance!
PS: I've looked at the SQL database too, but it doesn't help much. The variables seem to have different naming conventions from the column names.
I think it should look like this because I have been trying to convert auto menu as well!
$db = &JFactory::getDBO();
$menu = JTable::getInstance('menu');
$menu->menutype = $menutype;
$menu->title = $title;
$menu->alias = strtolower($title) ;
$menu->note = "Created by automenu";
$menu->path = $link;
$menu->link = $link;
$menu->type = $linktype;
$menu->published = $published;
$menu->parent_id = $menuparentid
$menu->level = $menusublevel;
$menu->componentid = $componentid;
$menu->ordering = 0;
$menu->checked_out = 0;
$menu->checked_out_time = 0;
$menu->browserNav = 0;
$menu->access = 1;
$menu->img = '';
$menu->templat_style_id = 0;
$menu->params = $params;
$menu->lft = 0;
$menu->rgt = 0;
$menu->home = 0;
$menu->language = '*';
$menu->client_id = 0;
I would be interseted to know if you ever got it working!
I'd suggest turning on Joomla debugging in the System Configuration. At the bottom of each page it shows all the queries it has executed, and this (depending on the plugin) might show you what SQL is being executed, and presumably, failing. There's likely to be a big list, so you may have to search through it a bit to find the statement you're interested in.
Fabio,
Many thanks! I will try it out and see if I can improve it further.
Mike
You're forgetting the first rule of Exceptions Club, if you throw something... you have to catch it.
I don't see a try/catch pair in your code so PHP would be stopping with a "Fatal Error..." for the uncaught exception so it would never get to the DEBUG 1. e.g.
Fatal error: Uncaught exception 'Exception' with message ...
Try wrapping your code in a try/catch pair and allowing the execution to continue after DEBUG 2 have a look at the PHP doc's for exceptions

Windows programming - send email script

Looking for a simple script that would run on windows 2003 server that would basically send me an email. What I plan to do us the windows services auto recovery manager to trigger the script.
I did find a reference to how I can trigger the use of this script: How to monitor Windows services
But I need some help on writing an send email script that would work for windows platform. I'm not sure what language would be best for this. thanks.
One simple way would be to use javascript (or VBscript). If you google for "Server.CreateObject("CDO.Message")" you will find more examples.
Put the code below in a file with extension: ".js", for example email.js
To call use "cscript email.js" on the command line. Replace server name and emails with valid values.
Windows 2003 should have CDO installed. The script used to work on windows XP and server 2003. This example uses smtp server over the network but there are other options too.
Powershell is probably available for server 2003 .. so it could be another option.
============================== code ==============================
function sendMail ( strFrom, strTo, strSubject, strMessage ) {
try {
objMail = Server.CreateObject("CDO.Message");
objConfig = Server.CreateObject("CDO.Configuration");
objFields = objConfig.Fields;
with (objFields) {
Item("http://schemas.microsoft.com/cdo/configuration/sendusing")= 2;
Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")= "xxxxsmtp.xxxserver.xxorg";
Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")= 25;
Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30;
Update();
}
with (objMail) {
Configuration = objConfig;
To = strTo; //"\"User\" ,"\"AnotherUser\" ;"
From = strFrom;
Subject = strSubject;
TextBody = strMessage;
//if we need to send an attachement
//AddAttachment("D:\\test.doc");
Send();
}
}
catch(e) {
WScript.Echo(e.message);
return false;
}
delete objFields;
delete objConfig;
delete objMail;
return true;
}
//WScript.Echo('qqq');
sendMail( 'from#xxxxxx.com', 'to#yyy.com' , 'test', 'msg');

Azure Storage Queue very slow from a worker role in the cloud, but not from my machine

I'm doing a very simple test with queues pointing to the real Azure Storage and, I don't know why, executing the test from my computer is quite faster than deploy the worker role into azure and execute it there. I'm not using Dev Storage when I test locally, my .cscfg is has the connection string to the real storage.
The storage account and the roles are in the same affinity group.
The test is a web role and a worker role. The page tells to the worker what test to do, the the worker do it and returns the time consumed. This specific test meassures how long takes get 1000 messages from an Azure Queue using batches of 32 messages. First, I test running debug with VS, after I deploy the app to Azure and run it from there.
The results are:
From my computer: 34805.6495 ms.
From Azure role: 7956828.2851 ms.
That could mean that is faster to access queues from outside Azure than inside, and that doesn't make sense.
I'm testing like this:
private TestResult InQueueScopeDo(String test, Guid id, Int64 itemCount)
{
CloudStorageAccount account = CloudStorageAccount.Parse(_connectionString);
CloudQueueClient client = account.CreateCloudQueueClient();
CloudQueue queue = client.GetQueueReference(Guid.NewGuid().ToString());
try
{
queue.Create();
PreTestExecute(itemCount, queue);
List<Int64> times = new List<Int64>();
Stopwatch sw = new Stopwatch();
for (Int64 i = 0; i < itemCount; i++)
{
sw.Start();
Boolean valid = ItemTest(i, itemCount, queue);
sw.Stop();
if (valid)
times.Add(sw.ElapsedTicks);
sw.Reset();
}
return new TestResult(id, test + " with " + itemCount.ToString() + " elements", TimeSpan.FromTicks(times.Min()).TotalMilliseconds,
TimeSpan.FromTicks(times.Max()).TotalMilliseconds,
TimeSpan.FromTicks((Int64)Math.Round(times.Average())).TotalMilliseconds);
}
finally
{
queue.Delete();
}
return null;
}
The PreTestExecute puts the 1000 items on the queue with 2048 bytes each.
And this is what happens in the ItemTest method for this test:
Boolean done = false;
public override bool ItemTest(long itemCurrent, long itemCount, CloudQueue queue)
{
if (done)
return false;
CloudQueueMessage[] messages = null;
while ((messages = queue.GetMessages((Int32)itemCount).ToArray()).Any())
{
foreach (var m in messages)
queue.DeleteMessage(m);
}
done = true;
return true;
}
I don't what I'm doing wrong, same code, same connection string and I got these resuts.
Any idea?
UPDATE:
The problem seems to be in the way I calculate it.
I have replaced the times.Add(sw.ElapsedTicks); for times.Add(sw.ElapsedMilliseconds); and this block:
return new TestResult(id, test + " with " + itemCount.ToString() + " elements",
TimeSpan.FromTicks(times.Min()).TotalMilliseconds,
TimeSpan.FromTicks(times.Max()).TotalMilliseconds,
TimeSpan.FromTicks((Int64)Math.Round(times.Average())).TotalMilliseconds);
for this one:
return new TestResult(id, test + " with " + itemCount.ToString() + " elements",
times.Min(),times.Max(),times.Average());
And now the results are similar, so apparently there is a difference in how the precision is handled or something. I will research this later on.
The problem apparently was a issue with different nature of the StopWatch and TimeSpan ticks, as discussed here.
Stopwatch.ElapsedTicks Property
Stopwatch ticks are different from DateTime.Ticks. Each tick in the DateTime.Ticks value represents one 100-nanosecond interval. Each tick in the ElapsedTicks value represents the time interval equal to 1 second divided by the Frequency.
How is your CPU utilization? Is this possible that your code is spiking the CPU and your workstation is much faster than your Azure node?

Resources