Securing password for use with .RegisterTaskDefinition()
I’m working on a helper function that registers a new task in Task Scheduler. The task is triggered by Event id 400, in the Windows PowerShell event log. The function is working as desired, with one exception- I am unable to secure the password. When passing in a SecureString I get a Type mismatch error. Is there any way I can use a secure credential here? Using a plain text password is not a valid option for me. I was unable to use the PSScheduledJob module, because New-JobTrigger does not seem to support ‘When a specific system event occurs’ as a trigger yet.
I’ve tried:
$taskRunasUserPwd = Read-Host 'Enter Your Password: ' –AsSecureString
and
$creds = Get-Credential
Then for the password value passed in:
$creds.Password
Both of these attempts yield this error message:
ERROR: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) qpo.ps1 (28, 1): ERROR: At Line: 28 char: 1 ERROR: + $rootFolder.RegisterTaskDefinition($name, $TaskDefinition, 6, $taskRu ... ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ERROR: + CategoryInfo : OperationStopped: (:) [], COMException ERROR: + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException ERROR:
Here is the full function:
#helper function
function Register-CustomTask
{
param (
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$TaskName,
[int]$EventId = 400,
[string]$Subscription = "<QueryList><Query Id='0'><Select Path='Windows PowerShell'>*[System[(EventID='400')]]</Select></Query></QueryList>"
)
Set-StrictMode -Version latest
try
{
$Hostname = $Env:computername
$Service = new-object -ComObject ("Schedule.Service")
$Service.Connect($Hostname)
$RootFolder = $Service.GetFolder("\")
$TaskDefinition = $Service.NewTask(0)
$regInfo = $TaskDefinition.RegistrationInfo
$regInfo.Description = "$TaskName"
$regInfo.Author = "$env:USERNAME"
$settings = $taskDefinition.Settings
$settings.Enabled = $true
$settings.StartWhenAvailable = $true
$settings.Hidden = $false
$Triggers = $TaskDefinition.Triggers
$Trigger = $Triggers.Create(0)
$Trigger.Id = $EventId
$Trigger.Subscription = $Subscription
$Trigger.Enabled = $true
$Action = $TaskDefinition.Actions.Create(0)
$Action.Path = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
$Action.Arguments = "Import-Module Foo; New-Foo"
$taskRunAsUser = $env:USERNAME
#TODO secure password
$taskRunAsUserPwd = Read-Host 'Enter Your Password: '
$rootFolder.RegisterTaskDefinition($TaskName, $TaskDefinition, 6, $taskRunAsUser, $taskRunAsUserPwd, 1)
Clear-Variable -Name taskRunAsUserPwd
}
catch { Write-Warning "Could not create task..." }
}
Register-CustomTask -TaskName 'foo'
edit: escaped angle brackets in $Subscription parameter