ITMS Administrator Group

 View Only

Start an Altiris Task from PowerShell using PoshAltiris 

Sep 03, 2016 02:51 PM

I wanted to give a little demo of a function constructed using the PowerShell PoshAltiris module to show how you might use it to programmatically execute tasks / jobs by name on the Altiris server usinng PowerShell

The cmdlet that we want to use is called Invoke-Task there is no existing help for this because Symantec has not provided any documentation on the webservice in their ASDK. I do know from running Help Invoke-Task though that it is going to require three parameters to run successfully (taskGuid, executionName and inputParameters) 

PS C:\> help invoke-task

NAME
    Invoke-Task

SYNOPSIS


SYNTAX
    Invoke-Task [-taskGuid] <Guid> [-executionName] <String> [-inputParameters] <String> [-Server] <String>
    [[-Credential] <PSCredential>] [<CommonParameters>]

I did a quick Google and found some sample code for this webservice from Lcode (Also using PowerShell, but I think you will like using the module much better).

It looks from his code to be something similar to the following for a description of the required parameters:

taskGuid - The Guid of the task you would like to execute

executionName - The name of the instance of the task you would like to show in the NS console

inputParameters - An xml file that houses required parameters (@AssignedResources and @CompRequirements) which I can describe a bit further here:

  • @AssignedResources - A comma delimited string containing Guids for resources you would like to target with the task (We know from how the console works this could either be the Guid of a collection / filter or a computer)
  • @CompRequirements - Short for completion requirements. Three settings are available here MinWaitTime, MaxWaitTime and MinCompletion (I can't find any more documentation on these and their possible formats)
  • Additional input parameters that are created on a job are created using <paramater><name>NameHere</name><value>ValueHere</value></parameter>

Cool! But looks kind of complicated to gather all of that information. So lets break down exactly what we would need to do to make this as simple as giving a function an array of computernames and a taskname and watching the magic happen.

 

Step 1 - Get the taskGuid from the task name

This is pretty straightforward

Get-ItemsByName -itemName $TaskName -Server $Server

 This will return an XML value containing an array of items that matches the task name I gave in Altiris. To parse into the first value of the array of items returned and get the Guid I modify the code to the following

$TaskGuid = @((Get-ItemsByName -itemName $TaskName -Server $Server).ArrayOfItemDetails.ItemDetails)[0].Guid

Now I have my TaskGuid value!

 

Step 2 - Choose an Execution Name

Looks like most execution names in the console just default to "Run $TaskName". Simple and classy. I like it.

$ExecutionName = "Run $TaskName"

 

Step 3 - Create the Input Parameters

Okay, now comes the more difficult part. I want to do this from an array of computer names right? The input parameters though expects a comma delimited string containing Guids for all of my computers! 

*Onset of fear begins.... immediately turns to running Get-Command*

PS C:\> Get-Command *computer* -Module poshaltiris

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Get-ComputerByNameAndDomain                        0.0.2      poshaltiris
Function        Install-AltirisAgentToComputers                    0.0.2      poshaltiris

 

Sick! What does this Get-ComputerByNameAndDomain cmdlet return!?

PS C:\> Get-ComputerByNameAndDomain -name $Env:COMPUTERNAME -domain $Env:USERDOMAIN -Server $Server

xml                            guid
---                            ----
version="1.0" encoding="utf-8" guid

 

Miracle of miracles! Okay, now this shouldn't be so bad.

$ArrayOfComputerNames = @("Computer1","Computer2","Computer3")

[string[]]$ComputerGuids = foreach ($Computer in $ArrayOfComputerNames) {
        (Get-ComputerByNameAndDomain -name $Computer -domain $Domain -Server $Server).guid."#text"
    }

 

Now to merge that into my inputParamaters xml and call it.

$InputParameters = @"
<inputParameters>
    <parameter>
        <name>@AssignedResources</name>
        <value>$($ComputerGuids -join ",")</value>
    </parameter>
    <parameter>
        <name>@CompRequirements</name>
        <value>
            <minWaitTime>2 minutes</minWaitTime>
            <maxWaitTime>60 minutes</maxWaitTime>
            <minCompletion>100 %</minCompletion>
        </value>
    </parameter>
</inputParameters>
"@

Invoke-Task -taskGuid $TaskGuid -executionName "Run $TaskName" -inputParameters $InputParameters -Server $Server

 

And now I should be able to verify and watch my task get executed from the NS console!

 

Now I took this and built it out a bit more into a reusable function that allows you to change some of the parameters and add additional parameters with some examples if you want to play around with it a bit.

 

Example #1 - with additional input parameters specified

$Computers = @("Computer 1", "Computer 2")
$TaskName = "That one task I've always wanted to run from PowerShell but was never able to until now"

$CompletionRequirements = @{
    "minWaitTime"="2 minutes"
    "maxWaitTime"="60 minutes"
    #Space here is deliberate between number and percentage. Again... couldn't find documentation on this.
    "minCompletion"="100 %"
}

$AdditionalParameters = @{
    "NEWCOMPUTERNAME" = "Hello"
}

$Server = "myserver.mydomain.com"

Invoke-TaskOnComputers -TaskName $TaskName `
                        -ComputerName $Computers `
                        -CompletionRequirements $CompletionRequirements `
                        -Server $Server -Domain $env:USERDOMAIN `
                        -AdditionalParameters $AdditionalParameters

 

Example #2 - No additional input parameters specified

$Computers = @("Computer 1", "Computer 2")
$TaskName = "That one task I've always wanted to run from PowerShell but was never able to until now"

$CompletionRequirements = @{
    "minWaitTime"="2 minutes"
    "maxWaitTime"="60 minutes"
    #Space here is deliberate between number and percentage. Again... couldn't find documentation on this.
    "minCompletion"="100 %"
}

$Server = "myserver.mydomain.com"

Invoke-TaskOnComputers -TaskName $TaskName `
                        -ComputerName $Computers `
                        -CompletionRequirements $CompletionRequirements `
                        -Server $Server -Domain $env:USERDOMAIN

 

 

Full Function Code (Invoke-TaskOnComputers)

Function Invoke-TaskOnComputers {

    param(
        [parameter(mandatory=$True)]
        [string]$TaskName,
        [parameter(mandatory=$True)]
        [string[]]$ComputerName,
        [parameter(mandatory=$True)]
        [Hashtable]$CompletionRequirements,
        [parameter(mandatory=$True)]
        [string]$Server,
        [string]$Domain = $env:USERDOMAIN,
        [Hashtable]$AdditionalParameters,
        #Default your Windows credentials will be used to  authenticate to the NS server.
        [pscredential]$AlternateCredential
    )

    # Getting the guid of the task from the name. Possibly better to use Get-ItemsByNameAndType for a safer experience.
    $TaskGuid = @((Get-ItemsByName -itemName $TaskName -Server $Server).ArrayOfItemDetails.ItemDetails)[0].Guid

    [string[]]$ComputerGuids = foreach ($Computer in $ComputerName) {
        (Get-ComputerByNameAndDomain -name $Computer -domain $Domain -Server $Server).guid."#text"
    }

    #Building the input parameters XML
    $InputParameters = @"
<inputParameters>
    <parameter>
        <name>@AssignedResources</name>
        <value>$($ComputerGuids -join ",")</value>
    </parameter>
    <parameter>
        <name>@CompRequirements</name>
        <value>
            <minWaitTime>$($AdditionalOptions["minWaitTime"])</minWaitTime>
            <maxWaitTime>$($AdditionalOptions["maxWaitTime"])</maxWaitTime>
            <minCompletion>$($AdditionalOptions["minCompletion"])</minCompletion>
        </value>
    </parameter>
$(
        if($AdditionalParameters) {
            foreach ($Parameter in $AdditionalParameters.Keys) {
                @"
    <parameter>
        <name>$Parameter</name>
        <value>$($AdditionalParameters[$Parameter])</value>
    </parameter>
"@
            }
        })
</inputParameters>
"@

    Invoke-Task -taskGuid $TaskGuid -executionName "Run $TaskName" -inputParameters $InputParameters -Server $Server

}

 

Statistics
0 Favorited
11 Views
0 Files
0 Shares
0 Downloads

Tags and Keywords

Comments

Oct 02, 2019 07:20 AM

What fixed it?

Have you raised an Issue on GitHub?

Oct 02, 2019 06:33 AM

I found that the issue was with incorrect ASDK.NS, ASDK.SMF referances. Thanks

Sep 27, 2019 09:25 AM

Thank you.

Yes, I am able to print the output values and alsp access the link http://localhost/Altiris/ASDK.NS/itemManagementService.asmx.

GetItemsByNameAndType
GetItemsByNameAndType : The term 'GetItemsByNameAndType' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ GetItemsByNameAndType
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (GetItemsByNameAndType:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 

get-help GetItemsByNameAndType

Name                              Category  Module                    Synopsis                                        
----                              --------  ------                    --------                                        
Get-ItemsByName                   Function  PoshAltiris               Returns the details of an item                  
Get-ItemsByNameAndType            Function  PoshAltiris               Find an item by its name and/or type.           
Get-ItemsByType                   Function  PoshAltiris               Returns all items of the given type in the NS

 

Thank you

Sep 26, 2019 02:51 PM

If you print

  • $newPackageName

  • $server

Does this output values?

---

If you navigate on the Altiris Server and run the API manually in IE does it work with the above values?

http://localhost/Altiris/ASDK.NS/itemManagementService.asmx

  • GetItemsByNameAndType

Sep 26, 2019 12:26 PM

Hi All,

I am getting the below error after execuiting the below command.

$checkIfSoftwareReleaseExists=Get-ItemsByNameAndType -Name $newPackageName -type "Altiris.SoftwareManagement.Resources.SoftwareReleaseResource" -Server $server

Error message

Invoke-RestMethod :
   
        Runtime Error
         
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida
Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        
     
            Server Error in '/' Application.
             Runtime Error
            
Description: An exception occurred while processing your request. Additionally, another
exception occurred while executing the custom error page for the first exception. The request has been
terminated.

 

I am trying PoshAltiris with Symantec Management Console Version 8.5.4249.

 

Thank you.

Mar 18, 2017 08:44 AM

AWESOME! Thank you for posting that up.

Mar 11, 2017 02:09 PM

Sharing is caring

Mar 10, 2017 12:35 PM

Ok this is quite a large script. In our environment we create 5-6 command lines and 3-4 filters and policies per package we import....this script checks the package source directory and looks for all of our standard VBScripts and creates coresponding command lines/filters/policies for the scripts that it finds. Most of that is company specific, so I've ripped out most of the itterations and it is only creating two command lines and one install policy.

This is working extremely well in our environment, I'm able to import a new package and create 4 policies/filters to our standards in seconds.

I posted two things:

The full script, scrubbed and trimmed down a bit as described above:
https://gist.github.com/MacDogbert/297c5309d8d185fbc1db25dfff5e3a11

A much shorter version to make it easier to see the PoshAltiris commands that are doing the work:
https://gist.github.com/MacDogbert/139e46f9876d14a6897e99418e9033a9

Apologies if it is hard to read, feel free to post questions here or on the gist. Also any suggestions/improvements welcome!

Mar 10, 2017 10:36 AM

Yes please do post the commands. I am very interested in seeing how you are able to get all this working. Thank you Josh.

Mar 10, 2017 10:05 AM

Post it up!!!

Mar 10, 2017 08:45 AM

Hi vintwala,

I haven't used Import-SoftwareRelease, but I am using New-SoftwareRelease successfully. I am using it as part of a script that creates a new software release, package, command lines, filters, policies, and detection rule. It is very specific to how we deploy software, but I can post an outline of the commands if that would be helpful.

Feb 01, 2017 09:15 AM

Thank you guys for a quick response ... appretiate it. Another question I have is:

Has anyone been successful using the "Import-SoftwareRelease" command using poshaltiris?  If you have can you please provide an example of what you had to do to get it working.

I went through the help file and some of the required parameters say "If empty will be extracted from package" ... but in my case it didn't exactly work the way it was suggested. Tried .msi and .exe file but still no successs.

Please do let me know if you are able to get the "Import-SoftwareRelease" command working using the poshaltiris module.

Feb 01, 2017 05:59 AM

You could look at the following for ideas with Task creation:

Jan 31, 2017 11:51 PM

Gotcha!

It does not look like the ASDK currently includes methods for the creation of tasks other than below:

New-SWTaskPackageDelivery
New-SWTaskQuickDelivery
New-SWTaskSourcePathUpdate
New-SWTaskVirtualization
New-SWTaskWindowsInstallerRepair

They are all software related tasks though. Sorry :(

Might be a good suggestion to put in for something to add to the ASDK though!

 

Jan 31, 2017 03:13 PM

Thank you Micah R for your response. I did find out how to start a script task. But I am looking for a way to create a new script task. Not sure if I can use poshaltiris to create a new script task.

Thanks again!

Jan 31, 2017 01:44 PM

Hi vintwala,

The same procedure outlined here would be used to start a script task.

Thank you,

Micah R

Jan 19, 2017 02:24 PM

Is there a way to create a run script task using poshaltiris? 

Sep 10, 2016 12:16 AM

So... I actually looked everywhere except for in the ASDK chm file because I foolishly thought my code to merge that help file with PowerShell functions was working perfectly lol.

I corrected the bug though and now the Help for Invoke-Taks looks like this! Thank you! Update-Module PoshAltiris should get you the latest version of PoshAltiris if you want it.

 

PS C:\Users\wmrm.NA\OneDrive - HAWORTH INC\Documents\GitHub\PoshAltiris\PoshAltiris> help Invoke-Task -Full

NAME
    Invoke-Task
    
SYNOPSIS
    Immediately executes a task or job.
    
    
SYNTAX
    Invoke-Task [-taskGuid] <Guid> [-executionName] <String> [-inputParameters] <String> [-Server] <String> [[-Credential] <PSCredential>] 
    [<CommonParameters>]
    
    
DESCRIPTION
    

PARAMETERS
    -taskGuid <Guid>
        The guid of the task or job to execute.
        
        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -executionName <String>
        The name given to this instance of the task or job execution.
        
        Required?                    true
        Position?                    2
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -inputParameters <String>
        Xml-formatted input parameters for the task or job.
        
        Required?                    true
        Position?                    3
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -Server <String>
        
        Required?                    true
        Position?                    4
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -Credential <PSCredential>
        
        Required?                    false
        Position?                    5
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see 
        about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). 
    
INPUTS
    
OUTPUTS
    
NOTES
    
    
        The value of the "inputParameters" parameter must be a string containing XML in a schema that defines the input parameters, and their values, that 
        you want to pass to the selected Task. Each Task has its own set of input parameters, defined by that Task. Consequently, the parameter names and 
        values in this ASDK method's "inputParameters" XML must match the previously-defined input parameters belonging to the Task you choose to run. This 
        method will ignore any parameters you provide whose name does not match the name of an existing Input Parameter for your chosen Task.
        The Input Parameters of a Task may be required or optional. Again, this is defined by the Task itself and is not affected by anything you pass in 
        via the "inputParameters" parameter XML of this ASDK method. You must pass in a parameter name and value for every required Input Parameter of the 
        Task. You MAY, but do not HAVE to, provide a parameter name and value for any Input Parameter that the Task has defined as optional. If the task or 
        job does not take any input parameters, pass in the Empty String.
        See the sample XML in the Examples section, below.
        NOTE: Both the parameters @AssignedResources and @CompRequirements are required in the input XML. When using the input parameter named 
        "@AssignedResources," the GUID(s) you pass in must represent existing GuidCollection(s) (Altiris.Common.GuidCollection). Each of the Guid 
        Collections may contain any combination of computer(s), resource collection(s), organizational view(s), or resource target(s). When using 
        @OverrideMaintenanceWindows the value can be either 'true' or 'false'.
        The following table lists and describes the valid elements of the "inputParameters" XML:
        XML Element NameDescriptionParent ElementRequired?
        <inputParameters>The root elementN.A.Yes
        <parameter>Contains a name and value for a Task input parameter, which will be passed to the task you choose to run.<inputParameters>A separate 
        <parameter> element is required for each input parameter you wish to pass in to the Task.
        <name>The name of the Task's Input Parameter, as defined by the Task itself.<parameter>Yes, if a <parameter> element is present
        <value>The value you give to this Task Input Parameter.<parameter>Yes, if a <parameter> element is present
        <minWaitTime>The number of minutes or hours to wait for 100% before checking for the minimum percentage.<value>This element is used only with a 
        parameter named "@CompRequirements". (See the reference to data type "ClientTaskCompletionRequirements" in the table below).
        <maxWaitTime>The maximum number of minutes or hours to wait for the minimum percent complete before the task fails.<value>This element is used only 
        with a parameter named "@CompRequirements". (See the reference to data type "ClientTaskCompletionRequirements" in the table below).
        <minCompletion>The number or percent of computers required to complete before moving on.<value>This element is used only with a parameter named 
        "@CompRequirements". (See the reference to data type "ClientTaskCompletionRequirements" in the table below).
        
        The following table lists the valid .NET 4.1 data types for values given to the Task Input Parameters and how those data types are to be 
        represented in the XML's <value> element(s):
        Input Parameter Data TypeHow Represented in the XML
        System.Guid00000000-0000-0000-0000-000000000000
        Altiris.Common.GuidCollectionA comma-separated list of GUID's
        System.StringPlain text
        System.Int32 (integer)Numerals in plain text
        System.DateTimeText formatted in any of the accepted DateTime formats, e.g., YYYY-MM-DD HH:MM:SS
        System.Boolean"true" or "false"
        Altiris.TaskManagement.Common.ClientTask.ClientTaskCompletionRequirements<minWaitTime>1 minutes</minWaitTime> <!-- acceptable values are integers 
        followed by any of: minutes, hours -->
        <maxWaitTime>10 minutes</maxWaitTime> <!-- acceptable values are integers followed by any of: minutes, hours -->
        <minCompletion>95 %</minCompletion> <!-- acceptable values are integers followed by any of: %, computers -->
    
    -------------------------- EXAMPLE 1 --------------------------
    
    PS C:\>CopyC#
    
    Guid taskGuid = new Guid("74b4e850-bdcf-4c09-876d-2ddc223dac8d");
    string inputXml = @"
    <inputParameters>
    <parameter>
        <name>@AssignedResources</name>
        <value>4404f03f-8001-4054-b86e-344e43b778f9, c2258340-be59-4051-9c89-3af1d53d33de</value>
    </parameter>
    <parameter>
        <name>@CompRequirements</name>
        <value>
                <minWaitTime>1 minutes</minWaitTime>
                <maxWaitTime>10 minutes</maxWaitTime>
                <minCompletion>95 %</minCompletion>
        </value>
    </parameter>
    <parameter>
        <name>@OverrideMaintenanceWindows</name>
        <value>
            <boolean>true</boolean>
        </value>
    </parameter>
    </inputParameters>";
    Guid taskInstanceGuid = m_proxy.ExecuteTask(taskGuid, "Some Name", inputXml);
    CopyVBScript
    taskGuid = "74b4e850-bdcf-4c09-876d-2ddc223dac8d"
    inputXml = _
    "<inputParameters>" & _
    "    <parameter>" & _
    "        <name>@AssignedResources</name>" & _
    "        <value>4404f03f-8001-4054-b86e-344e43b778f9, c2258340-be59-4051-9c89-3af1d53d33de</value>" & _
    "    </parameter> " & _
    "    <parameter> " & _
    "        <name>@CompRequirements</name>" & _
    "        <value>" & _
    "                <minWaitTime>1 minutes</minWaitTime>" & _
    "                <maxWaitTime>10 minutes</maxWaitTime>" & _
    "                <minCompletion>95 %</minCompletion>" & _
    "        </value>" & _
    "    </parameter>" & _
    "    <parameter>" & _
    "        <name>@OverrideMaintenanceWindows</name>" & _
    "        <value>" & _
    "            <boolean>true</boolean>" & _
    "        </value>" & _
    "    </parameter>" & _
    "</inputParameters>"
    taskInstanceGuid = taskManagement.ExecuteTask(taskGuid, "Some Name", inputXml)
    Copy? 
    set inputXml="<inputParameters><parameter><name>@AssignedResources</name><value>4404f03f-8001-4054-b86e-344e43b778f9, 
    c2258340-be59-4051-9c89-3af1d53d33de</value></parameter><parameter><name>@CompRequirements</name><value><minWaitTime>1 
    minutes</minWaitTime><maxWaitTime>10 minutes</maxWaitTime><minCompletion>95 %</minCompletion>   
    </value></parameter><parameter><name>@OverrideMaintenanceWindows</name><value><boolean>true</boolean></value></parameter></inputParameters>"
    set taskGuid="74b4e850-bdcf-4c09-876d-2ddc223dac8d"
    AltirisASDKTask.exe cmd:ExecuteTask taskGuid:%taskGuid% executionName:"Some Name" inputParameters:%inputXml%
    Remarks
    The CLI is being deprecated. Please see the CLI Programming Guide.
    
    
    
    
    
RELATED LINKS

 

Sep 09, 2016 07:03 AM

Sweet! Thanks Network23

Sep 09, 2016 03:47 AM

Hi tiberriver256,

Great article!

Regarding minWaitTime, maxWaitTime and minCompletion I found the following in the ASDK.chm File ..

asdk_8.0.png

Network23

Related Entries and Links

No Related Resource entered.