Powershell script to schedule daily task error
Asked Answered
M

2

8

I have a very simple power shell script that will register console applications as daily scheduled tasks.

$TaskCommand = Read-Host 'Enter the path to the console application'
$TaskName = "TaskName"
$TaskStartTime = "10PM"
$TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted"

$TaskAction = New-ScheduledTaskAction -Execute "$TaskCommand" -Argument "$TaskArg"
$TaskTrigger = New-ScheduledTaskTrigger -At $TaskStartTime -Daily
Register-ScheduledTask -Action $TaskAction -Trigger $TaskTrigger -TaskName "$TaskName" -User %computername%\theusername -Password "password" -RunLevel Highest

The application reads the file path from user input and attempts to register the application as a task using a specific user account. I can get the script working by using

-User "System"

However when I try to use the above script I get this error:

Register-ScheduledTask: No mapping between account names and security IDs was done.

I have ensured that the account exists as it is currently running several services. I am also new to powershell so have tried adding quotations around the username with no luck.

Maudemaudie answered 19/6, 2017 at 13:6 Comment(0)
E
8

Don't think PowerShell recognises %computername%. Have a look at environment variables here.

$env:USERNAME, $env:USERDOMAIN $env:COMPUTERNAME look relevant to your task.

Estrous answered 19/6, 2017 at 13:12 Comment(0)
I
1

For me, it was an issue of having trailing spaces where the variables were stored. Unrelated to the question at hand, but perhaps a sanity-check worth pursuing for others who reads this.

Indian answered 15/7, 2020 at 11:18 Comment(1)
(If you want not to receive votes on an answer, edit it and set it to Community Wiki).Alica

© 2022 - 2024 — McMap. All rights reserved.