• View Communities
    • Citrix Developer Network
      The place for unfiltered straight talk on Citrix products. Blogs, code downloads, best practices, APIs, and more can all be found here.
    • Citrix Ready Community Verified
      Does it work with Citrix? Application compatibility questions are a thing of the past with the new Citrix Community Verified site.
    • Blogs
      Learn the latest from the Citrix employees who are building application delivery infrastructure technologies.
    • Blogosphere
      The Citrix Blogosphere is a window into the thousands of conversations taking place about Citrix and Application Delivery.
  •  Sign In
The Citrix Blog
Blogs for tag 'powershell'

Permalink | Twitter Post to Twitter | Comments (0) | Views (864) |


The most common request we get for Power and Capacity Manager is the support for other power management APIs... With XenApp 5.0 Feature Pack 2, we only support Wake-on-LAN and XenServer API. We will extend this list in upcoming versions.

In the meanwhile, your only option is to use WMI events to trigger power-on commands to your computer management infrastructure.

I've tested the following using Powershell V2. The script has to run in the Concentrator:

Register-WmiEvent -Namespace "ROOT\Citrix\XenAppPCM" -SourceIdentifier "PowerEventAction" -Query "Select * from __InstanceModificationEvent within 10 where TargetInstance ISA 'Server' and TargetInstance.PowerActionState=4" -Action {
   $servers = Get-WMIObject -Namespace "ROOT\Citrix\XenAppPCM" -Query "Select * from Server Where PowerActionState=4"
   foreach ($s in $servers)
   {
     #Launch power action command to the server management infrastructure here
     Write-Host $("Server: " + $s.Name + " MAC: " + $s.MacAddress)
   }
}

PCM classes in WMI are registered under ROOT\Citrix\XenAppPCM namespace. The script above registers a listener that triggers when PCM changes a server "PowerActionState" attribute to 4 – this state indicates PCM needs additional capacity for a workload.

Another interesting event in PCM WMI is "NotEnoughCapacityEvent". This event triggers when all servers in the workload are on-line, but policies would require additional servers to become on-line. You could use this to trigger provisioning of additional servers in that workload.

PCM WMI classes are pretty feature rich. In fact, all console operations issue WMI operations under the covers. You can find the MOF files after installing the Concentrator, at %WINDIR%\System32\WBEM\PCMConcentrator_v2.0.50727.mof and %WINDIR%\System32\WBEM\Framework\root\Citrix\XenAppPCM\PCMConcentrator_SNVersion_1.0.2.0.mof

You may also take a look at the Powershell WMI Explorer from thepowershellguy.com (link), it's a pretty decent WMI browser using nothing but Powershell!

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (2940) |

posted by Ed York

One of the most common questions I've heard on Workflow Studio is how you can initiate the execution of workflows from an ASP.NET web page.  The web is a great platform for delivering applications to end-users, and more and more applications are being delivered by a web browser each day.  How cool would it be to kick off a workflow within Workflow Studio based on a user-action performed inside a web application?  In this blog I'm going to show you how to do it and I'll give you the tools to customize this further to meet the needs of your application.

Example Usage
Before I go into the details about how the sample web application works, I want to quickly provide an example of why you may want kick off workflow execution from a web page.  As you think about your business, ask yourself what it takes to get a new hire set up with new credentials across all of the systems in your environment.  You need an Active Directory account, application accounts, HR accounts, credentials supplied to your single sign-on solution, etc. 

To accommodate this scenario, you can build a web page that presents a form to an admin to gather details about a new user, what groups they should belong to, and what applications/resources they need to access.  This web page can call a workflow within Workflow Studio passing in the details about the user, and the workflow can automate the provisioning of the Active Directory account and application accounts across various systems.  That's a pretty powerful system and would greatly simplify a lot of the complexities for performing those actions manually.  Building that type of workflow might take some custom development effort, but Workflow Studio 1.1 already provides activities for provisioning user accounts in Active Directory to help get you started.

ASP.NET Web Application Overview
The sample web application that I'm providing here is functionally equivalent to the sample Windows application that I provided in the last blog.  To compare and contrast the differences between automating workflows with a Windows and Web application, I wanted to keep the functionality and UI mainly the same.  The web version of the application is shown below.


I describe my adventures for coding this application in the bottom of this article.  To sum up, this application really has two parts.  You have the ASP.NET application that contains the ASPX page and code-behind page.  You also have a COM object that you need to install inside Component Services. (I have steps for doing all this below). 

When you click the Execute Workflow button inside the web page, the ASPX page gathers what workflow you are executing and what runtime it is deployed on.  It then calls the COM object to actually execute the workflow.  The COM object uses the Workflow Studio Powershell cmdlets for communicating with Workflow Studio.  I was getting security issues when I tried to run those functions within the context of IIS.  By creating a COM object and placing that object within Component Services, I was able to overcome the issues I was having. 

For more information on how this application works, feel free to check out the previous article of this blog series.  I described in great detail how the Windows version of this application functions, so I'll refer you to that article for the extra details.  For more information on why I needed to build the COM object, refer to the Lessons Learned section at the bottom of this article.

Downloads:
Download the ASP.NET web application IIS files
Download the ASP.NET web application source code

Prereqs for using the ASP.NET application:
Before you set up this web application on your Workflow Studio machine, you will need to have the following installed and/or configured beforehand:

  • Workflow Studio 1.1
  • Powershell 1.0
  • IIS installed with ASP.NET enabled
  • IIS configured with the ASP.NET v2.0.50727 web service extension set to Allowed
  • Determine or specify an account within the Workflow Studio Console for executing the workflows.  This is done within the Security section.
  • Pre-deploy the Workflow you want to execute within the Workflow Studio Console.  See Part 1 of this blog series for more information.

Setting up the ASP.NET application:
To set up this sample web application, follow the steps in the sections below.

Application Setup

  • Copy the IIS files from the ZIP above to C:\Citrix (or any accessible location on your Workflow Studio machine)
  • Update the web.config file with the appropriate impersonation account.  This account should have permissions to execute workflows within Workflow Studio and should be the same account that is added to Component Services later in these steps.  

IIS Setup

  • Open IIS and create a virtual directory for the application.  Point the virtual directory to the folder specified above.  Enable script execution on the directory.
  • View the properties of the virtual directory in IIS. In the ASP.NET tab, set the ASP.NET version to 2.0.50727.

Component Services Setup

  • Launch Component Services by navigating to Start->All Programs->Administrative Tools->Component Services
  • Within Component Services, navigate to Computers->My Computer->COM+ Applications.  Right-click COM+ Applications and select New->Application
  • The wizard now starts.  Create an empty application
  • Specify a name such as "WFSCOM" and select Server Application
  • Set the application identity to a Workflow Studio admin account
  • Create a new role called "Access"
  • Add the Workflow Studio admin account to the Access role
  • Complete the wizard
  • After the COM+ application is created, add a new component to the COM+ application.  Navigate to Computers->My Computer->COM+ Applications->WFSCOM->Components.  Right-click Components and select New->Component.
  • The wixard now starts.  Choose to install a new component
  • Browse to the WFSCOM.dll file (C:\Citrix\WFSWebClient\bin\WFSCOM.dll).
  • Complete the wizard

You should now see the WFSCOM.WFSAction COM object listed within the Components section.  In the Interfaces section, there is an inteface called IWFSAction that contains the methods of our COM object.  The ASP.NET code calls the COM object to execute these methods.  Since this object resides inside Component Services, these methods run outside the context of IIS under the Workflow Studio admin account that we specified above. 


Lessons learned from developing this application
Developing an ASP.NET web application that executes workflows actually turned out to be a little more difficult than building the equivalent Windows application.  With a Windows application, the application runs under the context of the logged-on user account. If that logged on user had permissions to execute workflows inside Workflow Studio, that user would be able to use the custom Windows application without issues.  With a Web application, the application runs under the context of IIS.  You can modify the account that runs a web application in a few places.  (1) Editing the properties of the virtual directory or (2) Including a <identity impersonate="true"> tag inside the web.config file of the ASP.NET application. 

Armed with that knowledge I set out to build the ASP.NET application.  The approach I initially took was to take all of the code I had inside the Windows application and paste it into the ASPX page and code-behind page.  The only thing I changed was I replaced all of the Windows controls with Web controls and I changed how I sent messages back to the user.  When debugging this application inside Visual Studio, my application actually ran fine.  However when I deployed it to IIS and ran it, that was a different story.  I kept on getting Access Denied messages whenever I wanted to retrieve the workflow list or execute a workflow.  Something inside those functions was causing me issues...

After much debugging, I deduced that the code that was causing the Access Denied messages was when I was trying to get a reference to the deployed workflow inside my PowerShell SDK code.  For whatever reason, IIS just did not have the permissions to execute the Workflow Studio Powershell cmdlet called get-deployedworkflow.  I put this section of code below so you are aware of which section I was having issues with.

//Get reference to the deployed workflow. We are executing the Powershell command below:
//$workflow = get-deployedworkflow -workflowruntime $runtime -workflowname $strWorkflowName -includeschedule
l_objPipeLine = l_objRunspace.CreatePipeline();
l_objCommand = new Command("get-deployedworkflow");
l_objCommand.Parameters.Add("workflowruntime", l_objRuntime);
l_objCommand.Parameters.Add("workflowname", l_strWorkflowName);
l_objCommand.Parameters.Add("includeschedule");
l_objPipeLine.Commands.Add(l_objCommand);
l_objCommandResults = l_objPipeLine.Invoke();   //Get Access Denied here when running this code in IIS
PSObject l_objWorkflow = l_objCommandResults[0];
l_objPipeLine = null
 
 

After playing with the Virtual Directory account settings and web.config impersonation settings for a while, I still was not able to get past the Access Denied message.  I would have thought that setting the web.config <identity> tag to the Workflow Studio admin account would have done the trick, but I still received that error message.  So I then I went to Plan B and thought of a different approach.  What if I take that particular code outside of IIS and put it into a more controlled environment where I can run it under whatever account I want and not have to worry about IIS getting in the way? 

That solution was Component Services.  I'm not an everyday developer (probably have one development project a year), but I remembered using Component Services many years back with a MFCOM application I wrote.  (MFCOM is the XenApp API).  With that application, I wanted to be sure that my MFCOM code would run under the context of a XenApp admin account and not the logged on user account.  So creating a COM object and placing that object within Component Services allowed me to run it under whatever account I needed.  With Component Services, you also have the choice of running the COM object in-process as a library application or out-of-process as a server application.  When you run it out of process, it is executed within a different memory space than the calling application.  Creating a COM object and executing it as a server application under the context of a Workflow Studio admin account was the missing ingredient for the Web Application that I was building.  Since it runs out-of-process, IIS can't get in the way and mess with those security permissions any more!

Although most of the Workflow Studio cmdlets functioned fine when running within IIS, I decided to move the entire Powershell SDK functions themselves to the COM object that I would run within Component Services.  Although this sounds really complicated, the good news is that I've done all the work for you.  The COM object that I am providing within this article has all the functions you need for executing a workflow.  If you want to create your own ASP.NET application that executes workflows, you just need to add my COM object to Component Services on your Workflow Studio machine, and then call the methods of the COM object inside your ASPX page.  If you are reading this article, I would venture to guess that you might have quite a bit of experience in working with ASP.NET so you should have the tools you need to proceed from here. 

About the source code:
The source code above includes both the ASP.NET web application and the COM object for executing the workflows.  Your development machine will need Visual Studio 2008, Workflow Studio, Powershell 1.0, Powershell SDK, and IIS. 

If you want to step through the code within Visual Studio, you'll need to place the COM object within Component Services on your development machine.  You can follow the manual steps above for doing this or use the regsvcs utility.  To use regsvcs.exe, open the Visual Studio command prompt and type a command such as this:

regsvcs /c "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\WFSWebClient\WFSCOM\bin\Debug\WFSCOM.dll"
 
 

I tried to code the COM object so that you wouldn't need to make any changes to it if you just wanted to execute workflows on Workflow Studio.  If you do need to make changes to the COM object for any reason, remove the COM object from Component Services.  If you placed the COM object within the global assembly cache (GAC), remove it from the GAC as well.  (The GAC resides in C:\Windows\Assembly.  Just right-click on the WFSCOM assembly to un-install it).  Then open the Visual Studio solution and make changes to the WFSCOM project as you need to.  Re-compile the project.  When you are ready to re-deploy the COM object, add WFSCOM.dll to the global assembly cache (GAC) to get a new type library (.tlb file).  To add it to the GAC, just execute a command such as below.  Then re-add WFSCOM.dll back to Component Services using the regsvcs command above.  If you open Component Services, you should now see the WFSCOM COM+ application listed.

gacutil.exe /i "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\WFSWebClient\WFSCOM\bin\Debug\WFSCOM.dll"
 
 


I hope this blog series on automating Workflow Studio will help you out with your projects.  Happy coding!

Blogs in this series:
Using Powershell to automate workflow execution within Citrix Workflow Studio
Passing parameters into a workflow within Citrix Workflow Studio
Automating workflow execution for Citrix Workflow Studio using a .NET windows application
Automating workflow execution for Citrix Workflow Studio using an ASP.NET web application (this one)

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (2952) |

posted by Ed York

This is the third part of a four-part series on automating workflow execution within Citrix Workflow Studio.  In the first two parts of the series, I discussed how you can create Powershell scripts to execute workflows.  Part 1 provided a high-level overview of creating Powershell scripts for automating workflow execution and Part 2 expanded on those scripts to discuss how to pass parameters into the workflow.  In this blog, I will discuss how you can automate workflow execution with a custom Windows application.  The sample .NET application I built is shown below.  I am providing both the executable and full source code to allow you to expand upon this solution to meet the needs of your environment.



When would I need to use a custom application for executing workflows?
A lot of you might be asking the question - "If we can use the Workflow Studio Console to execute workflows, why would I need a custom application to do that for me?".  The answer really comes down to how you need to execute certain workflows in your environment.  If you need to execute workflows "on-demand" or "on a schedule", the Workflow Studio Console would meet those needs.  Just open the Workflow Studio Console and schedule a job to run immediately or on a pre-determined schedule.  However, if you need "event-driven" automation where a third-party application kicks off the execution of a workflow based on an event happening, that is where you need to be able to hook into Workflow Studio with a custom solution to perform that type of automation. 

The custom application provided in the Downloads section below provides a sample for how you can tie any .NET windows application to Workflow Studio for executing workflows.  Feel free to try out the sample application on your Workflow Studio machine.  The full source code is also provided to allow you to customize and extend the application further based on what you need to do.

Downloads:
Download the application executable here
Download the application source code here
 

Preparing your Workflow Studio environment to use the custom application:
The custom application needs to run on a machine that contains Workflow Studio since it ties into Powershell and calls the Workflow Studio cmdlets for performing various actions on Workflow Studio.  In your Workflow Studio Console, you will need to pre-deploy the workflow that you want to automate (see Part 1 for more information on pre-deploying workflows).  The workflow that you want to automate can include parameters as well.  Parameters for a workflow are defined in the Workflow Studio Designer under the Global Properties section (see Part 2 for more information on defining workflow parameters).

This custom application functions as any typical Windows application in that it runs under the context of the logged-on user account.  The logged-on account needs to have permissions in Workflow Studio to execute workflows.  These permissions are defined in the Security section of the Workflow Studio Console.  For simplicity, I typically add the user accounts as a "Workflow-Admin", but you can play with the security roles here to determine what roles are actually needed.



Using the custom application:
To use the custom application, log onto your Workflow Studio machine with an account that has permissions to execute workflows within Workflow Studio.  Place WFSWorkflowExecute.exe on your Workflow Studio machine.  When you launch the application, the initial view is shown below.



Click the Get Runtimes button to get the Workflow Studio runtimes that are installed on the local machine.  The runtimes are listed within the combo-box below and the name of the runtime specifies which account the runtime is running under.  



When a runtime is selected, all of the workflows that are deployed on that runtime are listed as well.  To execute a certain workflow, you need to know which runtime you deployed the workflow on.   This sample application also provides the version of the workflow as you may have deployed two different versions of the same workflow to the same runtime.  Using the version numbers helps you keep them straight.

When you want to execute a workflow, you need to know if that workflow requires any parameters.  The workflow parameters are defined in the Workflow Studio Designer in the Global Properties section of the workflow.  As mentioned above, Part 2 of this blog series goes into detail on how to define and use parameters inside a workflow.



When specifying workflow parameters inside the custom application, the parameter name is case sensitive.  (Notice how I kept the parameter name as "gMessage").  If you mistype the parameter name or use the wrong case, you will get an error message when executing the workflow stating that the parameter name is not recognized.  Just keep this in mind as you type the name of the parameters into the application.



Click the Execute Workflow button to execute the workflow.  If the workflow was successfully executed, you'll get a pop-up message indicating success.



To verify the workflow was executed, you can open the Workflow Studio Console and check out the Jobs section. 



Understanding the source code:
A lot of you out there will want to customize this application in your own environment.  I developed this application with C# using Visual Studio 2008 and the Powershell SDK.  Your development machine will also need Powershell 1.0 and Citrix Workflow Studio.  For advice on setting up your Visual Studio environment, check out this article.  If you follow the steps in that article, you'll just need to add the Powershell SDK and you should be all set.

The Powershell SDK is included as part of the Windows Software Development Kit.  You can get information on the Poweshell SDK here.  I downloaded the full ISO and it took me quite a while to get it.  When you are ready to install, you don't need everything in the setup wizard.  The Powershell SDK link provided above actually tells you what you specifically need to install to just get the Powershell SDK.  To use the Powershell SDK inside your Visual Studio project, the project will need to reference System.Management.Automation.dll.  

Once you get your development machine set up, you can open the solution that I provided above inside Visual Studio.  Essentially all this custom application does is use the Powershell SDK APIs to execute cmdlets on Powershell.  Since Workflow Studio provides Powershell cmdlets to automate various tasks, we can use the Powershell SDK to automate many Workflow Studio functions. 

From my personal experience, using the Powershell SDK takes a little time getting used to.  What I found to be helpful is to first write out the Powershell commands in Notepad and test them within Powershell to make sure they are functioning as expected.  If you are working with Powershell variables, use the echo statement frequently to understand the current value of the variable.  Then when you are ready to use the Powershell SDK in your Visual Studio project, you can convert each of your Powershell statements to the equivalent Powershell SDK code.  In the source code that I provided for this custom application, I put comments into the code to explain what Powershell command I was trying to execute within that code block.  Reviewing those comments should help you to get started with understanding how to use the Powershell SDK.  For example, here is the ExecuteWorkflow() function that is used by the custom application.  Stepping through this code inside Visual Studio and watching the variables is another great way to learn this code.

public string ExecuteWorkflow(Hashtable objFunctionParameters, Hashtable objWorkflowParameters)
{
   try
   {
      //Declare local variables
      string l_strReturn = "Executing workflow";
      string l_strWorkflowName = objFunctionParameters["WorkflowName"].ToString();
      string l_strRuntimeName = objFunctionParameters["RuntimeName"].ToString();
      Hashtable l_objWorkflowParameters = objWorkflowParameters;

      //Create a runspace containing the Workflow Studio snap-ins
      RunspaceConfiguration l_objRSConfiguration = RunspaceConfiguration.Create();
      PSSnapInException l_objSnapInException = null;
      l_objRSConfiguration.AddPSSnapIn("Citrix.WorkflowStudio.Azman", out l_objSnapInException);
      l_objRSConfiguration.AddPSSnapIn("Citrix.WorkflowStudio.Core", out l_objSnapInException);
      l_objRSConfiguration.AddPSSnapIn("Citrix.WorkflowStudio.DataStore", out l_objSnapInException);
      l_objRSConfiguration.AddPSSnapIn("Citrix.WorkflowStudio.Installer", out l_objSnapInException);
      Runspace l_objRunspace = RunspaceFactory.CreateRunspace(l_objRSConfiguration);
      l_objRunspace.Open();

      //Get reference to the Workflow Studio runtime that was passed in.
      //We are executing the Powershell command below:
      //$rt = Get-WorkflowRuntime -ServiceName $ServiceName
      Pipeline l_objPipeLine = l_objRunspace.CreatePipeline();
      Command l_objCommand = new Command("get-workflowruntime");
      l_objCommand.Parameters.Add("ServiceName", l_strRuntimeName);
      l_objPipeLine.Commands.Add(l_objCommand);
      Collection<PSObject> l_objCommandResults = l_objPipeLine.Invoke();
      PSObject l_objRuntime = l_objCommandResults[0];
      l_objPipeLine = null;

      //Get reference to the deployed workflow that was passed in.
      //We are executing the Powershell command below:
      //$workflow = get-deployedworkflow -workflowruntime $rt -workflowname $strWorkflowName -includeschedule
      l_objPipeLine = l_objRunspace.CreatePipeline();
      l_objCommand = new Command("get-deployedworkflow");
      l_objCommand.Parameters.Add("workflowruntime", l_objRuntime);
      l_objCommand.Parameters.Add("workflowname", l_strWorkflowName);
      l_objCommand.Parameters.Add("includeschedule");
      l_objPipeLine.Commands.Add(l_objCommand);
      l_objCommandResults = l_objPipeLine.Invoke();
      PSObject l_objWorkflow = l_objCommandResults[0];
      l_objPipeLine = null;

      //Schedule the workflow to run immediately.
      //We are executing the Powershell command below:
      //schedule-workflow -workflowruntime $rt -workflowstrongname $workflow.WorkflowStrongName -workflowparameters $wfparameters -runimmediately
      l_objPipeLine = l_objRunspace.CreatePipeline();
      l_objCommand = new Command("schedule-workflow");
      l_objCommand.Parameters.Add("workflowruntime", l_objRuntime);
      l_objCommand.Parameters.Add("workflowstrongname", l_objWorkflow.Properties["WorkflowStrongName"].Value.ToString());
      l_objCommand.Parameters.Add("workflowparameters", l_objWorkflowParameters);
      l_objCommand.Parameters.Add("runimmediately");
      l_objPipeLine.Commands.Add(l_objCommand);
      l_objCommandResults = l_objPipeLine.Invoke();
      l_objPipeLine = null;

      //Close the runspace
      l_objRunspace.Close();

      //Return success
      l_strReturn = "Job completed!";
      return l_strReturn;
   }
   catch (Exception objException)
   {
      //Initialize error message
      string l_strError = "";
      l_strError = "An error has occurred. The error is \"" + objException.Message.ToString() + "\". ";
      return l_strError;
   }
}

Blogs in this series:
Using Powershell to automate workflow execution within Citrix Workflow Studio
Passing parameters into a workflow within Citrix Workflow Studio
Automating workflow execution for Citrix Workflow Studio using a .NET windows application (this one)
Automating workflow execution for Citrix Workflow Studio using an ASP.NET web application






Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (3) | Views (3960) |

posted by Peter Schulz


Jason Conger and Brandon Shell did a little video debate at Synergy on PowerShell vs. Workflow Studio. You can view it here:
http://community.citrix.com/x/cgRqB

So, who do I think is right? That is easy - they both are!

First I want to say thank you to both of these guys for getting a discussion going. If I can paraphrase Brandon's side of the argument it would be "Why do I need Workflow Studio? I have Windows PowerShell." This is a question I have gotten a lot and I want to take some time to address it here.

Workflow Studio is designed to run on top of PowerShell. PowerShell 1.0 is a pre-requisite and many of our activities are written in PowerShell. Like Brandon, I think that PowerShell is an excellent scripting language and I personally can't wait for the day when everything is in PowerShell and there is no more need for VBScript. I believe every Windows administrator should learn PowerShell and use it regularly. I am doing what I can to drive all Citrix products to expose an SDK in PowerShell.

So wait a minute then... if the Product Manager for Workflow Studio is saying to use PowerShell then what is Workflow Studio for?

There is no reason that you should have to decide between the two technologies. If you are a Citrix customer then you have Workflow Studio at no additional cost. Workflow Studio has a great SDK for consuming PowerShell libraries, so you can leverage your existing PowerShell libraries with Workflow Studio. Here are some other things you can do with Workflow Studio:

  1. Workflows are stored centrally in a SQL database making sharing and re-use across your team much easier
  2. Workflows are automatically versioned when stored in the database. If you update a workflow that has been deployed, a copy is automatically created so you can continue to reference and use the previous version.
  3. Workflow Studio is integrated with a task scheduling interface to automate the execution of your workflows based on schedule.
  4. Workflow Studio has a simple, graphical, drag and drop interface. Most likely not everyone on your team is a PowerShell expert. Workflow Studio provides a simple interface that lets those not familiar with PowerShell be productive with it as well.
  5. Workflow Studio can easily integrate with things that aren't PowerShell (native libraries support VBScript, WMI, and running batch files. You can also use 'off-the-shelf' activity libraries for Workflow Foundation as well.)
  6. Workflow Studio is designed to support persistence. For simple, quick jobs, someone who is familiar with PowerShell and the cmdlets necessary to complete a given task will be more effective using the PowerShell command line interface. If the task requires several levels of approvals over hours, days, or even months then Workflow Studio and its underlying persistence and tracking engine from Workflow Foundation is a better tool for the job.

And remember, everything in Workflow Studio is exposed via PowerShell, so you can build your own interfaces to your workflows in PowerShell.

I would love to get more feedback on this topic in the comments. Let me know if you agree or disagree. Ultimately these are both just tools and if they don't help you do your job then they are meaningless. Let us know how we can make both technologies work better for your organization.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (2427) |

posted by Ed York

This is the second part of a four-part series on automating the execution of workflows within Citrix Workflow Studio.  In the first blog of the series, I discussed the basics for using Powershell to automate the execution of workflows.  In this blog, we will expand on that topic to discuss how we can pass parameters into the workflow, making our workflows much more dynamic and flexible for supporting different types of situations.

Understanding Global Properties
The key to passing parameters into a workflow is to use the global properties of the workflow.  You access the global properties within the Citrix Workflow Studio Designer by navigating to Workflow->Manage Global Properties from the file menu (shown below).


The Manage Global Properties dialog allows you to specify the global properties of the workflow.  Essentially, all you need to do here is to define the names of the global properties and their property type (String, Boolean, Integer, etc.).  I personally like to pre-fix my global properties with the letter "g" to make them easily identifiable when assigning them to activities.  You can also optionally define a default value for a global property if you want to.


Then within your workflow, you bind the global properties to the activities within the workflow.  When you edit a bindable property for an activity, you'll get an editor such as is shown below.  On the left-hand side, select Global Properties within the drop-down.  The global properties should all be listed and easily identifiable by the letter "g" in front of the name (if you named them this way).  Just select a global property and add it to the text editor to use it. 

When global properties are defined for a workflow, you define the values of the global properties when scheduling a job within the Workflow Studio Console




Creating a Powershell Script that passes parameters into the workflow
If you want to automate the execution of the workflow with Powershell, the Powershell script can also set the values of the global properties to pass into the workflow being executed. 

To pass parameters into the workflow, the Powershell script will have a structure similar to below.  This sample script shows how to pass two parameters into the workflow.  What we are doing here is creating a hash table that represents the name/value pairs of the global properties.  This hash table is then provided as a parameter into the schedule-workflow cmdlet.  Please note that the schedule-workflow cmdlet should be all on one line (it was split on two lines here for better readability).

#Set variables for the workflow
$strWorkflowName = "Workflow1"
$strParam1Name = "Name1"
$strParam1Value = "Value1"
$strParam2Name = "Name2"
$strParam2Value = "Value2"

#Add the Workflow Studio snap-ins to the current Powershell session
Get-PSSnapin -registered | Add-PSSnapin

#Get reference to the Workflow Studio runtime
$rt = Get-WorkflowRuntime

#Get reference to the deployed workflow
$workflow = get-deployedworkflow -workflowruntime $rt -workflowname $strWorkflowName -includeschedule

#Create hash table of parameter values to pass into workflow
$params = @{$strParam1Name = $strParam1Value; $strParam2Name = $strParam2Value}

#Schedule the workflow to run immediately
schedule-workflow -workflowruntime $rt -workflowstrongname $workflow.WorkflowStrongName
-workflowparameters $params -runimmediately


Example:
To illustrate how the passing of parameters works, let's use the SQL Server Activity Library within our workflow. This is an activity library that you can download and leverage yourself for communicating with a SQL Server database.  The beginning point of our workflow is shown below. 


In this workflow, we are using the SQLExecute activity for executing an UPDATE command on a SQL Server database.  The initial SQL UPDATE command is shown below.  Since we are hardcoding the Employee ID and Phone Number into the SQL statement here, the initial usability of this workflow is pretty limited.  It would be much better if we could make this SQL statement adaptable for different employee IDs and phone numbers.


To make this SQL statement more dynamic, we need to create global properties to represent the Employee ID and Phone Number.  Notice the prefix "g" we are using to denote the global properties.  This will make them easy to find when applying them to an activity.


Once the global properties are defined, we can use them within the SQLExecute activity.  In the screen shot below, the SQL Command is updated to reference the global Employee ID and Phone Number properties created above.


Our workflow is pretty dynamic now.  We can pass the Employee ID and Phone Number as parameters into the workflow.  When the workflow is executed, it will use the passed in values as part of this SQL statement.

The Powershell Script to automate the execution of this workflow is shown below.  Please note that the schedule-workflow cmdlet should be all on one line (it was split on two lines here for better readability).

#Set variables for the workflow
$strWorkflowName = "Workflow1"
$strParam1Name = "gEmployeeID"
$strParam1Value = "101"
$strParam2Name = "gPhoneNumber"
$strParam2Value = "555-123-4567"

#Add the Workflow Studio snap-ins to the current Powershell session
Get-PSSnapin -registered | Add-PSSnapin

#Get reference to the Workflow Studio runtime
$rt = Get-WorkflowRuntime

#Get reference to the deployed workflow
$workflow = get-deployedworkflow -workflowruntime $rt -workflowname $strWorkflowName -includeschedule

#Create hash table of parameter values to pass into workflow
$params = @{$strParam1Name = $strParam1Value; $strParam2Name = $strParam2Value}

#Schedule the workflow to run immediately
schedule-workflow -workflowruntime $rt -workflowstrongname $workflow.WorkflowStrongName
-workflowparameters $params -runimmediately


Final thoughts:
If you want to try out these Powershell scripts yourself, you'll need to follow the setup instructions as outlined in the first blog of this series. 
In the final two blogs of this series, we are going to take these Powershell scripts to the next level by converting them to an actual C# program. As you'll soon see, you'll use the information contained in these first few blogs to understand how the C# programs actually work.  Stay tuned!

Blogs in this series:
Using Powershell to automate workflow execution within Citrix Workflow Studio
Passing parameters into a workflow within Citrix Workflow Studio (this one)
Automating workflow execution for Citrix Workflow Studio using a .NET windows application
Automating workflow execution for Citrix Workflow Studio using an ASP.NET web application

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (1) | Views (3903) |

posted by Ed York

When you begin learning Workflow Studio, you quickly learn that the Workflow Studio Designer can execute workflows for initial testing purposes and the Workflow Studio Console can execute workflows as a scheduled job.  A lot of people have been asking about how you can automate the execution of a workflow from an external system, such as Powershell, a Windows application, and an ASP.NET web application.  The real power of Workflow Studio is being able to execute a workflow when you want it to run, either manually, on a schedule, or on-demand when needed by external systems. 

This is the first blog of a new series I'm starting on how you can automate the execution of workflows from external systems, beginning with Powershell.  One thing I didn't realize when I started using Workflow Studio was how much this product was connected to Powershell.  Essentially, any action you can perform within the Workflow Studio Console has an equivalent Powershell cmdlet for it.  Using these cmdlets allows us to automate the various tasks within the Workflow Studio Console, such as executing the workflows themselves.

Workflow Setup:
If you want to execute a workflow with Powershell, the workflow needs to be in the Ready state within the Workflow Studio Console.  One thing that I prefer to do to keep the Powershell script fairly short is to pre-deploy the workflow to the Jobs section in the Workflow Studio Console.  When you pre-deploy a workflow, you are just making it available to execute as a Job without actually executing it yet.  By doing this simple step ahead of time, we can actually cut our Powershell script in half.  Please note that this is just a one time step - once you deploy it to the Jobs section you really don't have to open the Workflow Studio Console again (unless you want to make changes to your workflow itself).  The two screen shots below demonstrate how to pre-deploy the workflow to the Jobs section.


 

Registration of Xceed DLLs:
The Workflow Studio cmdlets leverage a few Xceed DLLs on the system.  These Xceed DLLs are part of the Workflow Studio installation and need to be present within the global assembly cache (GAC) in order for several of the Workflow Studio cmdlets to run properly.  Workflow Studio 1.1 does not actually place these DLLs into the GAC so you need to do that manually for this release.  I was told in future releases that this step will already be done for us.

There are three Xceed DLLs you need to place into the GAC:  Xceed.Compression.dll, Xceed.FileSystem.dll, and Xceed.ZIP.dll

Drag these DLLs from the C:\Program Files\Citrix\Workflow Studio folder to the C:\Windows\Assembly folder.  This process adds them to the GAC.  The end result is shown below.



Powershell Setup:
An interesting thing to note about Powershell is that scripting is turned off by default.  You can't execute a Powershell script until you enable scripting at a desired level.  I'm not exactly sure why Microsoft chose to do that since Powershell is supposed to be a scripting language, but it is fairly easy to enable scripting.

Launch Powershell (Start->Programs->Windows Powershell 1.0->Windows Powershell) and type the following command to get the current execution setting:

Get-ExecutionPolicy

If the execution policy is set to Restricted, you need to enable script execution by typing the following command:

Set-ExecutionPolicy RemoteSigned



Powershell Script:
The table below is a sample Powershell script for executing a workflow on your Workflow Studio machine.  I've tested the Workflow Studio cmdlets pretty extensively and this seems to be the simplest script I was able to create to execute a workflow. 

To use this script in your environment, just copy and paste this script into Notepad, and rename the file as a .PS1 file.  Then update the value of the $strWorkflowName variable to be the name of the workflow you want to execute.  In my next blog, I'll explain how you can tweak this script to pass parameters into the workflow.  The script below will work for any workflow that does not require parameters.

#Set variables for the workflow
$strWorkflowName = "Workflow1"
 
#Add the Workflow Studio snap-ins to the current Powershell session 
Get-PSSnapin -registered | Add-PSSnapin
 
#Get reference to the Workflow Studio runtime
$rt = Get-WorkflowRuntime
 
#Get reference to the deployed workflow
$workflow = get-deployedworkflow -workflowruntime $rt -workflowname $strWorkflowName -includeschedule
 
#Schedule the workflow to run immediately
schedule-workflow -workflowruntime $rt -workflowstrongname $workflow.WorkflowStrongName -runimmediately

Executing the Powershell script:
After the PS1 file is created, place it within an accessible place on your Workflow Studio machine.  For example, I've placed my scripts within C:\Citrix\PowershellScripts.  One thing I found out is that you want the path to the script to have no spaces, so keep that in mind as you place your PS1 file into a directory.

Next, open the Run window and type the statement below to execute your Powershell script (my script was called ExecuteWorkflow.ps1)
           powershell.exe -noexit C:\Citrix\PowershellScripts\ExecuteWorkflow.ps1

The -noexit switch above keeps the Powershell window open after the script is executed.  If the script execution was successful, you should see a Job ID as noted below.  This tells you that the workflow was successfully executed.



Troubleshooting the Powershell script:
If you are having issues with your Powershell script, the approach I typically take for troubleshooting is to launch Powershell and execute each line of the script manually until you come across the error.  Powershell can be launched from the Start Menu (Start->Programs->Windows Powershell 1.0->Windows Powershell) or by typing Powershell.exe in the Run window.

If you receive Access Denied errors, there is a good chance that the account you are running Powershell under is not a Workflow Studio admin, or does not have permissions within Workflow Studio to execute various workflow actions.  Check that your logged on user account is either a Workflow Studio admin or has these permissions.  These permissions are set inside the Workflow Studio Console within the Security section.

Most of the commands in the script above use variables.  To see the value of a variable, use the echo statement. For example:

echo $strWorkflowName

If the variable is an object, you can also display the value of its individual properties.  For example:
echo $workflow.WorkflowStrongName

If you want to see the list of all the Workflow Studio cmdlets, use this statement:





Get-Command -PSSnapin citrix*

The output of the above statement is shown below:


If you want more information on how to use a specific Workflow Studio cmdlet, use a statement such as this:

Get-Help schedule-workflow

Blogs in this series:

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (1) | Views (3414) |



Follow me on Twitter at @aurelianolopez

Customers who use XenApp for application management frequently use MFCOM and the Windows command line interface to control XenApp and even to create scripts and batch files. With PowerShell being adopted quickly, customers have asked us for support here as well. For the past few months, we have been working on just that and we recently finished out a phase 1 private tech preview that helped provide some much needed feedback on the direction we were going. We solicited feedback from some close members of our Citrix community and they provided the insight we needed to really make this work well for customers. You can still see those threads in the support forum.

I'm happy to announce that we've just released the Commands for XenApp Technology Preview. PowerShell Commands for XenApp allow you to access most aspects of XenApp including MFCOM functionality, Access Management Console features, and even functions found in the Advanced Configuration Tool (aka Citrix Management Console) and will work for XenApp 5 on W2K8 and on Presentation Server 4.5 with HRP03 running on Windows Server 2003 (aka XenApp 5 on W2K3). Commands for XenApp are an initial step towards the next generation of the Management SDK for XenApp. They will replace the current XenApp Management SDK (MPSSDK/MFCOM) in future releases so it's very important to us that customers that use the SDK's take a look at Commands and provide feedback before we release the final version. All customers and partners who currently use MFCOM can now experiment with this release and participate with us in the creation of the official release. We are looking forward to that feedback.

This Tech Preview is open to everyone with a MyCitrix account (Create a MyCitrix account if you don't have one yet). Download the tech preview from our new tech preview site and access the support forum if you need help and to provide feedback. The forum has separate sections for bugs, enhancement requests, scripts, and general questions and discussion.

Special thanks to Brandon Shell, Nick Holmquist, Jeroen van de Kamp and Tony Zhang for their suggestions and bug reports - their feedback was crucial for this second version. We are looking forward to your participation as well.

If you are interested in participating in future private previews of the XenApp SDK's, please contact me at twitter at @aurelianolopez.

Sncerely,

The XenApp Commands team

Check out these Other Links and Resources
XenApp Tech Preview Page
XenApp on Twitter
XenApp blogs
XenApp Videos and TV

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (3212) |

posted by Peter Schulz

I just posted an article on the components that are pre-requisites for Workflow Studio and how you can extend the ISO image we provided to include all components if you wish:

http://community.citrix.com/display/wf/Workflow+Studio+Pre-Requisites

I find it useful to have a CD image with everything on it that auto-runs, and thought that others might as well.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (5647) |

posted by Peter Schulz

I just posted a video tutorial on using the Workflow Studio SDK to to convert a PowerShell cmdlet to an activity library on the Multimedia section of the Workflow Studio CDN site

This tutorial walks you through creating an activity library from the Get-Date PowerShell cmdlet just like the tutorial in the Developer's guide. The SDK and Developer Guide is available here:
http://community.citrix.com/cdn/wf/sdks

Here is the video:

Getting Started with the Workflow Studio SDK

Get started converting your own favorite PowerShell cmdlets and let us know what you find.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (7054) |

posted by Peter Schulz

***Update: As of the 2.0 release we now include 143 activities with the product, including libraries for Netscaler, XenServer, and XenApp. We keep adding more, and if you have specific requests, please email me...

Alex posted in our forums that he was extremely disappointed in the 1.0 release of Workflow Studio because of a lack of libraries/templates for use with Citrix products. We are working on releasing libraries for Citrix products, as well as libraries that integrate with Active Directory, Group Policy, Power Management, and Windows. I appreciate the criticism, as it made me realize that we haven't done a good job of describing the target audience of this 1.0 release. I would like to take the opportunity to explain the different audiences that Workflow Studio appeals to, and why we released 1.0 as it is. Hopefully this post will help to explain how the different features of Workflow Studio appeal to these audiences and also clarify how it can be used today and where we are going in the future.

To make sure we are all on the same page, I want to start by defining the audiences that I will refer back to later. The titles I chose are not important, but hopefully the descriptions will help you to place where this fits in your organization. In the IT industry people often wear many hats and don't fit neatly into a classification.

  • IT Operations - This role is responsible for ensuring that IT systems are working and available on a wide scale, but would not typically do development or scripting tasks.
  • Server Administrator - This role is responsible for specific server workloads and is intimately familiar with the software running on a system. They are comfortable with batch files, scripting, PowerShell, etc. but would not be comfortable doing traditional software development.
  • Software Developer - This role is defined by people who write software that is either sold (Software Companies, System Integrators, Consultants, etc.) or used internally by other groups (often including the above two audiences.)

Workflow Studio is built on top of two technologies from Microsoft - Windows PowerShell and Windows Workflow Foundation. Linking these technologies to the audiences from above for PowerShell would be the Server Administrator, and for Workflow Foundation would be the Software Developer. Our intent with Workflow Studio is to merge these two technologies together and offer solutions that appeal to the IT Operations staff (and Server Administrators who are looking for tools, but are too busy to script solutions to all their needs themselves.) As a result of being built on top of PowerShell and Workflow Foundation, we offer features that the other two audiences will also find useful.

As Alex pointed out, the 1.0 release is not very interesting to the IT Operations audience yet because there isn't a large base of activity libraries and workflows available today. The Software Developer audience on the other hand can use 1.0 today with the publicly available APIs for our Citrix products (and if they choose, share or sell their work to the community at large.)

Now I want to take a look at specific features and functionality of Workflow Studio and how they map to these audiences:

IT Operations
The intended process of using Workflow Studio for this audience would be to download workflows (and activity libraries) that solve specific problems that this audience faces. All that needs to be done after downloading the workflows is to schedule or execute them as applications that solve those specific needs.

Workflow Studio has a community tab that links the product back to the Citrix Developer Network (CDN). Citrix, our partners, and the community at large can post activity libraries and workflows that can be downloaded and used without any need to write scripts or code. We built in a tutorial workflow called ExportServices that you can access through the Help menu to see how this process is intended to work. We plan to leverage this mechanism to release activity libraries and workflows to address specific problems faced in deploying the Citrix Delivery Center and the Citrix Cloud Center. We are also looking to our partners and community to build additional libraries and workflows that this audience will find valuable.

Obviously, this audience will not be well served until pre-built workflows are available that solve problems you face in your environment. Let me know in the comments or through email what types of things you would like to see. As we release activity libraries we will also release workflows that relate to them and as more are available we will be able to release more integrated workflows as well.

Server Administrator
The intended use case for this audience is to build and modify workflows using the Workflow Studio Designer for use either internally or to share with the community.

We are working on some activity libraries that will be available in coming weeks that will facilitate building workflows that leverage your existing VBScript and PowerShell scripts. This functionality will enable this audience to leverage their existing scripting knowledge in a more visual, database-driven, automatically versioned, and easily share-able way. Workflows can be extended through C# with the code-beside feature, so if you know a little bit of programming you can automate almost anything that .NET and C# will allow with just the Designer and not need to go into Visual Studio to build native activity libraries. We have built in some pretty powerful extensions to Workflow Foundation in our Designer that will help you be more productive and make it easy to share within your group, organization, or the community. For instance, the snippets functionality allows you to save templates of individual activity configurations or groups of activities and then export and reuse/share them. Workflows themselves can also be exported and reused/shared as well. The Workflow Studio Designer is accessed by either creating a New Workflow or editing an existing workflow. You can also download other workflows and edit them to see how they were built.

This audience needs activity libraries available, and we are working on several that will be released in coming months. Active Directory, Group Policy, Windows, Power Management, and Citrix product support are all coming soon, so stay tuned.

Software Developer
The intended use case for this audience is to build and share/sell activity libraries that the above two audiences will find useful. These can target Workflow Studio directly or target Workflow Foundation more generically as the vendors in my post on Workflow Studio Extensibility have done.

Activity Libraries are the mechanism for extending Workflow Studio. An activity library is a component defined by Microsoft as part of Workflow Foundation. These can be built without any knowledge of Workflow Studio (standard Workflow Foundation activity libraries), but there are some features of Workflow Studio that we think offer additional value. We make it easy to target Workflow Studio directly with a set of templates for Visual Studio. Specifically, we have a converter that will take existing PowerShell snap-ins and convert them to activity libraries automatically. You will soon be able to download these templates and documentation on automating Workflow Studio on our Download SDKs page.

Workflow Foundation and PowerShell have been around now for more than 2 years. These technologies are robust and stable and can easily be leveraged with the 1.0 release of Workflow Studio. If you are a Citrix partner (or want to be one) and have some ideas in this space, feel free to contact me to discuss.

Hopefully this will help clarify where we are with Workflow Studio and where we are going. Feel free to email me with comments or thoughts on how we can do a better job of addressing your needs with Workflow Studio - whichever audience you may fall into.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (2) | Views (11445) |


Brandon Shell (MVP PowerShell) and I are planning a more advanced level MFCOM and PowerShell Webinar to manage XenApp. We are looking for some input for the webinar content. Tell us what particular script or sample  code you would like to see via comments. If you would like us to demo a particular method or a call then please leave us a comment. We would try our best to include it in the webinar.

Follow the link provided to view the previous webinar where Brandon explained how to write MFCOM scripts using PowerShell to manage XenApp.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (6820) |

posted by Shannon Ma

I've developed a PowerShell snapin that gives you the ability to take and revert snapshots with XenServer 5.0. You can find more information about it (including the download) here.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (3) | Views (13972) |

posted by Jennifer Lang

On Wednesday, October 1st, I attended the Rocket Science 2008 and 2008 Application Virtualization Group (AVG) Engineering Expo. A few of the demos covered super top-secret innovations to improve the Engineering/Test process*, others were examples of demos for Summit and then there were four stations that really peaked my interest. That's not to say that everything else wasn't ubercool or that everyone that presented doesn't deserve MAJOR kudos for all the work they've done above and beyond their regular duties, but if you're attending Summit you can and should see those demos for yourself, and I think these particular entries deserve some notice.

Automating VM provisioning

Andy Zhu presented work for a virtualization initiative. The large-farm/scalability test team is employing XenServer in order to use virtual servers instead of physical servers for every test. The XenServer PowerShell Kit allows the team to quickly and easily deploy predefined templates to XenServer in a large scale. Using more virtual servers means no more brown-outs when System II powers up that 1001st server!

Cloning XenApp just got easier

Shannon Ma demonstrated the latest version of XenAppPrep, a tool that helps clone XenApp servers. In Shannon's words, it's basically the equivalent of sysprep for Windows, except it's for XenApp. Since I had just finished a round of virtualizing XenApp Server on XenServer Platinum utilizing the current tool and in the past I've helped create documentation about cloning XenApp Server, I know the manual process can be tedious so I really wanted to see "What's next?" XenAppPrep should be available on the web October 26th, and you're going to want it.

UPDATE: XenAppPrep is now available for download - http://community.citrix.com/display/xa/XenAppPrep+Tool

XenPool On-Demand Data Center

Kailas Jawadekar presented his latest work created for the internal XenPool initiative. Configured similarly to the public MyCitrixLab used by the Citrix Ready Program (more info on MyCitrixLab here and here,) the Citrix AVG XenPool is a project to demonstrate the benefits of pooling hardware resources in a lab environment and offering a set of dynamically configurable VMs to a broader set of customers. Kailas demonstrated a working model of a customer self-service frontend where someone that needs access to a VM can go to a webpage, choose from a selection of available templates and request a VM. When the VM is ready, the user gets an email to notify them. To ensure people aren't taking up resources they're not really using, the VMs come with a timed lease so a user receives prompts when the VM is about to expire and when the VM has reached it's expiration date so a user can elect to extend the lease time if they are still utilizing the VM.

Eating your own dog food can make you rich and thin

This last demo was the one that really put the cherry on top for me and reminded me just how much Citrix products can rock. Steve Dillon and the AVG Build team used our own technology to provide themselves High-Availability, Business Continuity, Disaster Recovery, reduced power consumption, reduced hardware and improved turn-around times. By incorporating XenServer Platinum Edition into their infrastructure, AVG Build went from 40 single CPU 32-bit servers to 2 16-core x64 servers running XenServer (4 quad-core CPUs per server.) By virtualizing on multi-processor machines and switching to x64-bit compatible software they were able to:

  • Reduce hardware ($aves space, reduces cooling costs, electricity, money . . .)
  • Speed the build machine provisioning process (what took hours now takes minutes)
  • Created a cost-effective DR solution instigated by Hurricane Wilma - there's now XenServers in the UK with Provisioning Server disk images ready to deploy and continue Build if local Build servers become unavailable.


Way to go, Citrites!

Finally, one last "Congratulations!" to everyone that participated this year - I can't wait to see what turns up next year - and "Thank you!" to David Pope, Gagan Singh and everyone that helped them put this event together for us.

* OK they're not all super top-secret, but thanks for reading down this far!

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (7) | Views (23186) |

posted by Ewan Mellor

Introduction


In this article I shall demonstrate the new XenServer PowerShell snap-in, using the simple example of "chained" VM starts: waiting for one VM to finish booting before starting the next.

The new SnapIn is available at http://community.citrix.com/cdn/xs/sdks.

In this example, we are using the XenServer Tools to detect when booting is complete: once they advertise the VM's IP address, we assume that the VM is ready. Of course, you may want to make this more sophisticated, for example waiting for a domain controller to start before moving on. I'll leave this to your imagination!

In the first screenshot, I've got XenCenter 5.0 talking to a XenServer 5.0 pool, XS-PS started afresh, and the script that runs this example, Start-VM.Wait.ps1. The PowerShell install is out-of-the-box, though I've already set the ExecutionPolicy to RemoteSigned.



Namespaces and Initialize-XenServer:Aliases


Firstly, a quick word about how we handle namespaces in XS-PS.

A lot of the Xen-API's names are very generic; a cmdlet called "Create-Message" could clash with any number of things. With this in mind, XenServer's cmdlets are named within a XenServer namespace, something like this:

Create-XenServer:VM
Destroy-XenServer:VM
Get-XenServer:VM
Get-XenServer:VM.NameLabel
Set-XenServer:VM.NameLabel
Invoke-XenServer:VM.Start

This is great for people who want to use XS-PS in a mixed environment, but it's obviously a bit verbose for quick scripting, so we've added the ability to alias these full names to something shorter. In Start-VM.Wait's process block, you can see the following call:

Initialize-XenServer:Aliases Start

This introduces a full set of aliases, so that we can now use names such as

Create-VM
Destroy-VM
Get-VM
Get-VM.NameLabel
Set-VM.NameLabel
Start-VM

These aliases are scoped within this script, so they won't pollute the user's environment. If you want, you can pass it a -Scope parameter, and have them put into an outer or global scope instead.

Initialize-XenServer:Aliases actually supports three styles of alias, so you can choose the style that best suits your environment, or you can stick with the full names if you prefer.

PS C:\Users\Ewan Mellor> Initialize-XenServer:Aliases
Invoke-Xen = Get-Xen:VM / Invoke-Xen:VM.Start
Invoke     = Get-VM / Invoke-VM.Start
Start      = Get-VM / Start-VM



Start-VM.Wait


Start-VM.Wait takes its VMs from the pipeline. It then processes them one at a time, like this:

  • If the VM record represents the control domain, or a template, then silently skip it.
  • If the VM is unstartable (because it's already running, say), then log the fact, and skip it.
  • Otherwise, call Start-VM. This will block until the VM boot process begins.
  • Next, wait for up to five minutes for the VM to boot. We wait for the VM.guest_metrics field to be populated, and for an entry to appear in VM_guest_metrics.networks. Once there's an entry here, we know that the XenServer Tools are ready, and the VM has an IP address configured (from DHCP, for example).
  • If polling this field fails after 5 minutes, then warn, and just move on to the next VM.


function Start-VM.Wait
{
    begin
    {
        $timeout = 5 * 60 * 1000
        Initialize-XenServer:Aliases Start
    }
    process
    {
        if ($_.is_a_template -or $_.is_control_domain)
        {
            return
        }
        if ($_.allowed_operations -notcontains "start")
        {
            Write-Warning("{0} cannot be started" -f $_.name_label)
            return
        }

        Write-Verbose("Starting {0}..." -f $_.name_label)
        Start-VM $_

        for ($count = 0; $count -le $timeout / 500; $count += 1)
        {
            $metrics = Get-VM.GuestMetrics $_
            if ($metrics -ne $null -and $metrics.networks.Count -gt 0)
            {
                Write-Verbose("VM {0} started" -f $_.name_label)
                return
            }
            Start-Sleep -m 500
        }

        Write-Warning("Timeout starting {0}" -f $_.name_label)
   }
}



Using it


Using this script is now very simple:

  1. Dot-source the script, to load the function.
  2. Set $VerbosePreference to "Continue", just for this demo.
  3. Connect to your master server.
  4. Choose the VM's that you want to start (in the example, all those tagged as "Production").
  5. Pipe those VM's into Start-VM.Wait.
  6. Watch the magic!
  7. Log out from your server afterwards.
PS> . .\Start-VM.Wait.ps1
PS> $VerbosePreference = "Continue"
PS> Connect-XenServer -url https://<servername>
PS> Get-XenServer:VM -Tags Production | Start-VM.Wait
...
PS> Disconnect-XenServer

This is a simple example, and no doubt you would want to tweak it to match your deployment, but I hope that it's enough of an example for you to get started.

Downloads


Start-VM.Wait.ps1

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (3) | Views (14834) |


The Citrix Desktop Delivery Controller PowerShell SDK provides a snap-in, XDCommands, for the Microsoft PowerShell v1.0 framework. The SDK consists of a number of "cmdlets" that allow you to script many of the administrative tasks you may need to perform on a regular basis.

Step by Step setting up your PowerShell / XenDesktop environment

  • Install PowerShell 1.0 on the DDC (Desktop Delivery Controller)
  • Download and Install Microsoft .NET Framework 3.5
  • The PowerShell SDK is located on the XenDesktop 2.1 CD in the ...\Support\DdcSdk folder. Run the installer XenDesktop_2_0_DDC_Powershell_SDK.msi

Installing the SDK registers the XdCommands snap-in assembly with the Microsoft PowerShell framework. The snap-in makes a number of new classes and "cmdlets" available to PowerShell scripts or interactive shell sessions.

To run scripts you may need to use the built-in "Set-ExecutionPolicy" cmdlet to adjust the PowerShell execution policy to a value such as "RemoteSigned"

  • Start Powershell and set the Excecution Policy. Set-ExecutionPolicy RemoteSigned
  • Change to the folder where the SDK is installed cd \Program Files\Citrix\Desktop Delivery Controller\Powershell
  • Load the snap-in into the PowerShell  Add-PSSnapin XdCommands

Alternatively, use the installed PowerShell console file, XdCommands.psc1, to start an interactive PowerShell shell session with the XdCommands snap-in pre-loaded. Citrix provides a shortcut on the Start menu to start such a session. This shortcut also runs the "XdAliases.ps1" PowerShell script that sets up aliases for most of the SDK cmdlets. This shortcut will not function properly until the PowerShell execution policy, as described above, is set appropriately.

Help

Online help is available for all Desktop Delivery Controller SDK cmdlets. To obtain a list of cmdlets offered by the snap-in, run the built-in "Get-Command" cmdlet, as follows: Get-Command -psSnapin XdCommands
Online help for individual cmdlets is available using the built-in "Get-Help" cmdlet. For example, to view the online help for the "Get-XdDesktopGroup" cmdlet, run the following command: Get-Help Get-XdDesktopGroup
For an overview of all cmdlets provided by the SDK, view the "about_XdCommands" help topic. To view this information, run the following command: Get-Help about_XdCommands

Samples

Creating a new VM-based desktop group

This command creates a new VM-based desktop group, "testgrp", containing three machines, and published to all domain users.
$usr = New-XdUser 'domain users' -group
$cred = Get-Credential 'root'
$hs = New-XdHostingServer 'XDS01' $cred
$machineName= 'machine1','machine2','machine3'
#find all the VM machines in the pool
$allvms = Get-XdHostedMachine $hs
#Find the workers and set the AD identity to the correct machine
$dsk = $machineName | foreach { $vm=$_; $allvms | where {$_.HostingName -match $vm } | foreach { $_.Name = $vm; $_ }}
$hgs = New-XdGroupHostingSettings $hs
$ng = New-XdDesktopGroup -pub 'testgrp' -desk $dsk -user $usr -hosting $hgs


Adding a virtual desktop to an existing VM-based desktop group

This command adds a new virtual desktop, hosted by a VM, to an existing VM-based desktop group. Before adding a VM to the group, you must create a mapping between the VMs host ID and Active Directory ID. To do this, run the Get-XdHostedMachine cmdlet to obtain a list of host IDs for VMs and assign Active Directory IDs to those VMs.

# get all the groups whose name starts with 'test' (should be just one)
$grp = Get-XdDesktopGroup test*
# get all the workers whose friendly names have 'machine3' in them (should be just one)
$dsk= Get-XdHostedMachine $grp.HostingSettings.HostingServer -name *machine3*
# Set up the mapping to the AD name for the new Virtual Desktop machine
$dsk.Name = 'machine3'
$grp.Desktops.Add($dsk)
Set-XdDesktopGroup $grp

If host ID to Active Directory ID mappings have been created previously, run the following command:

Get-XdDesktopGroup test* | *%* { \[void\]$\_.Desktops.Add($(Get-XdHostedMachine $\_.HostingSettings.HostingServer \-name \*machine3\*)); $\_ }| Set-XdDesktopGroup

Logging off a user from all current sessions, after sending a warning message

This command displays a warning message to all users whose names start with "christian" before logging them off. Note that in this example there is specified time period (10 seconds) before logoff occurs.

# get sessions for all users whose names start with 'christian'
$sess = Get-XdSession -user christian*
# warn the user
Send-XdSessionMessage $sess 'Forced log off in 10 seconds'
Start-Sleep 10
#Then go ahead with the logoff
Stop-XdSession $sess

Adding a user to an existing desktop group

This command adds users in all groups whose names match "GroupName" to an existing desktop group.
# get all the groups whose name matches 'GroupName' (should be just one)
# Note could also be written as:

#  $grp = Get-XdDesktopGroup GroupName
$grp = Get-XdDesktopGroup | ? {$_.Name -match "GroupName" }
$Usr = New-XdUser "UserName"
$grp.Users.Add($Usr)
Set-XdDesktopGroup $grp


Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (1) | Views (12621) |

posted by Ewan Mellor

Now that XenServer and XenCenter 5.0 have been released, we turn our attention to other things. One of those new projects is a PowerShell SnapIn for XenServer, which I'm pleased to announce today.

The new SnapIn is now available publicly, at http://community.citrix.com/cdn/xs/sdks.

Here are a few basic examples. Over the next few days, I'll post some increasingly interesting examples, to help you get a feel for the new SnapIn.

PS> Get-Credential | Connect-XenServer -url https://<servername>


PS> Get-XenServer:VM -name Debian | Format-Table uuid,name_label,is_a_template,power_state

uuid                name_label                is_a_template         power_state
----                ----------                -------------         -----------
2b676031-29b0-35... Debian Sarge 3.1                   True              Halted
b20f5359-1c5a-7b... Debian Etch 4.0                    True              Halted
9b14ee57-47fd-af... Debian Sarge 3.1...               False              Halted
04738c85-0bb7-ce... Debian Sarge 3.1                  False           Suspended
4b76320b-404b-0c... Debian Etch 4.0 (1)               False             Running
3e0982ed-0cfe-1e... Debian Sarge 3.1                  False           Suspended


PS> Get-XenServer:VM -name Debian -properties @{ is_a_template="false" } |
>>    Format-Table uuid,name_label,power_state

uuid                       name_label                               power_state
----                       ----------                               -----------
9b14ee57-47fd-afc6-e057... Debian Sarge 3.1 (1)                          Halted
04738c85-0bb7-ce5a-40bc... Debian Sarge 3.1                           Suspended
4b76320b-404b-0cdf-1583... Debian Etch 4.0 (1)                          Running
3e0982ed-0cfe-1ef5-7e5c... Debian Sarge 3.1                           Suspended


PS> Invoke-XenServer:VM.start -vm "Debian Sarge 3.1 (1)"
PS> Get-XenServer:VM -name Debian -properties @{ is_a_template="false" } |
>>    Format-Table uuid,name_label,power_state

uuid                       name_label                               power_state
----                       ----------                               -----------
9b14ee57-47fd-afc6-e057... Debian Sarge 3.1 (1)                         Running
04738c85-0bb7-ce5a-40bc... Debian Sarge 3.1                           Suspended
4b76320b-404b-0cdf-1583... Debian Etch 4.0 (1)                          Running
3e0982ed-0cfe-1ef5-7e5c... Debian Sarge 3.1                           Suspended

PS> Disconnect-XenServer -url https://<servername>
Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (3) | Views (9964) |


In my last blog I have started with the Introduction of PowerShell and MFCom. Today we'll provide you more information's about MFCom Objects and how to use them with PowerShell.

Check Session State


To retrieve the session state for each session within the Citrix farm you have to query IMetaFrameSession.SessionState. If the returned state of the session is MFSessionStateStale, no further attempt to read other session properties should be made. This state indicates that the session may no longer exist.
The following PowerShell script displays all active sessions within the farm and adds additional session information to the output. To check other session's states you only have to replace the session state type in the last line of the code.

#Type Definitions
$MetaFrameWinFarmObject =
 

$MFSessionStateUnknown = 0         #Unknown state
$MFSessionStateActive = 1          #User logged on
$MFSessionStateConnected = 2       #Connected to client
$MFSessionStateConnecting = 3      #Connecting to client
$MFSessionStateShadowing = 4       #Shadowing another session
$MFSessionStateDisconnected = 5    #Logged on but no client
$MFSessionStateIdle = 6            #Waiting for connection
$MFSessionStateListening = 7       #Listening for connection
$MFSessionStateResetting = 8       #Reset in progress
$MFSessionStateDown = 9            #Down due to error
$MFSessionStateInit = 10           #Initializing
$MFSessionStateStale = 11          #Stale session object
 

#Main
$farm = new-Object -com "MetaframeCOM.MetaframeFarm"
$farm.Initialize($MetaFrameWinFarmObject)
$farm.FarmName

$farm.Sessions | Where-Object { $_.SessionState -eq $MFSessionStateActive {color:black}}| Format-table Username,SessionName,AppName,ServerName,SessionState

Find disabled Application      

Finding disabled applications is mostly useful in your production or test environment where you have to handle with many published applications. This property IMetaFrameApplication.EnableApp enables or disables the application.

  • When you publish an application, it is enabled by default. Enabled applications are available to the users specified when the application was published. Disabled applications are not available to users.
  • The application can become disabled internally if its server list becomes empty, or if its user list becomes empty and the application is not configured to accept anonymous connections.
  • A disabled application is not available to clients.

#Type Definitions
$MetaFrameWinFarmObject = 1

#Main
$farm = new-Object -com "MetaFrameCOM.MetaframeFarm"
$farm.Initialize($MetaFrameWinFarmObject)
$farm.FarmName
$app = $farm.Applications
$app | foreach { $_ | ? { $_.EnableApp -eq 0 }}|Format-Table DistinguishedName

 

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (7922) |

posted by Peter Schulz

When you build a workflow using some of the PowerShell tasks you may come across a need for the special variable "$_". This variable represents the current pipeline object in PowerShell and is used in workflow tasks to refer to the passed in 'Input' object. One case where this comes up often is with the "Where-Object" task. When using this object your "Filter Script" property will typically contain something that looks like this:

$_.Status -eq "Running"

The above means to return all items from the Input object where the Status field is "Running"

I found this site that does a great job of explaining the special variables in PowerShell if you want to explore further:

http://www.computerperformance.co.uk/powershell/powershell_variables.htm

That site has a lot of tutorial pages on PowerShell covering the escape character I talked about in my previous post as well as a good summary of PowerShell syntax. I find myself on that site often from searching for PowerShell topics and often find answers there.

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (0) | Views (8257) |

posted by Peter Schulz

There was a question on the forums about calling the XenApp task Connect To Farm when using a domain user name. Since we are using PowerShell heavily under the covers the string passed in to this task for the username needs to use the PowerShell escape character whenever a reserved character for PowerShell is in the string. I searched Microsoft's site, but couldn't find much detail out there on this so I wanted to clarify here:

The escape character for PowerShell is the grave-accent character "`" (which on US keyboards should be in the upper-left of the keyboard to the left of the number 1.

I haven't been able to find much posted on reserved characters on Microsoft's site, but here is a good article that highlights what is in the PowerShell help documentation:

http://www.microsoft.com/technet/scriptcenter/resources/qanda/jan08/hey0117.mspx

Here is the list of characters from that article:

$
( )
*
+
.
[ ]
?
\
/
^
{ }
|

 If you need to use any of those characters in a string then you will need to escape it with the ` character. For example, to pass in a domain username to Connect to Farm in XenApp then you will need to pass in "domain`/user" instead of just typing "domain/user".

Expand Blog Post
Permalink | Twitter Post to Twitter | Comments (1) | Views (9435) |

posted by Peter Schulz

If you haven't read my post on whether we should have more customizable dialogs in Workflow Studio please check it out (here) and respond to the poll so I know what you think. In that post I mentioned that you could get custom dialogs today in Workflow Studio by leveraging PowerShell. Building Custom dialogs in PowerShell is not easy right now, but there are some projects out there to automate the process using the Visual Studio designer so it is getting easier. I'm not going to cover the specifics of how to create dialogs with PowerShell, but have a look at this Microsoft article for an introduction and then I will show you how to use this concept in Workflow Studio:

http://www.microsoft.com/technet/scriptcenter/resources/pstips/feb08/pstip0208.mspx

As I said, the process of building the dialog in PowerShell is tedious, but fortunately getting it into Workflow Studio is not so hard. Workflow Studio has a task called "PowerShell script" that can execute PowerShell script directly:

 
Just drag this task onto your workflow and paste the code from the above article into the "PowerShell Script" property. Now when you run your workflow you will get the dialog to appear. Pretty cool...
 
If you left all the defaults on your PowerShell Command task then you will also have the results of $x (the input string) in your $Output variable and you can use that in subsequent tasks.
 
In future articles I will look at how you can use this concept to create more complex dialogs and pass more complex objects out, but try it out and let me know what you think.

Expand Blog Post

1   2   Next >>