Private/New-SpecScheduledTaskAction.ps1
function New-SpecScheduledTaskAction { <# .SYNOPSIS This function creates a new scheduled task action based on the provided parameters. .DESCRIPTION The New-SpecScheduledTaskAction function creates a new scheduled task action based on the specified parameters. It supports creating actions for PowerShell scripts or other types of executable files. .PARAMETER IsPs1Script Indicates whether the action is for a PowerShell script. If this parameter is set to $true, the action will be configured to run a PowerShell script using powershell.exe. .PARAMETER path Specifies the path to the executable or script for the scheduled task action. .PARAMETER arguments Specifies the arguments to be passed to the scheduled task action if it is not a PowerShell script. If IsPs1Script is $true, a predefined set of arguments for running PowerShell scripts will be used instead. .PARAMETER startin Specifies the working directory for the scheduled task action if it is not a PowerShell script. Not used if it is a PowerShell script. .EXAMPLE $action = New-SpecScheduledTaskAction -IsPs1Script $true -path "C:\Scripts\MyScript.ps1" Creates a new scheduled task action to run a PowerShell script "MyScript.ps1" using predefined arguments. .EXAMPLE $action = New-SpecScheduledTaskAction -IsPs1Script $false -path "C:\Program Files\MyApp.exe" -arguments "-Option1" -startin "C:\Program Files\MyApp" Creates a new scheduled task action to run an executable "MyApp.exe" with the specified arguments and working directory. .NOTES Returns error code 910 if the settings could not be successfully configured. Author: owen.heaume Date: August 10, 2023 Version: 1.0 #> [cmdletbinding()] param ( [bool]$IsPs1Script, [string]$path, [string]$arguments, [string]$startin ) try { write-verbose "Assigning Task Action settings" #If it is a powershell script, then use the powershell.exe as the program and specify the arguments If ($IsPs1Script) { $taskAction = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$Path`"" } else { # If it is not a powershell script, then check if arguments or StartIn were used $taskAction = New-ScheduledTaskAction -Execute $Path if (![string]::IsNullOrEmpty($Arguments)) { # $arguments not null or empty then... $taskAction.Arguments = $Arguments write-verbose "Task Action arguments are set to: $($taskaction.arguments)" } if (![string]::IsNullOrEmpty($StartIn)) { # $startin not null or empty then... $taskAction.WorkingDirectory = $StartIn write-verbose "Task Action workingdirectory is set to: $($taskaction.workingdirectory)" } } write-verbose "Task Action settings assigned successfully" return $taskAction } catch { write-warning "Task Action settings could not be assigned: $x" return 910 } } |