1

I use this two commands in powershell to edit two scheduled tasks

schtasks.exe /tn Task1 /sd 2015-01-01  /ed 2015-02-02 /rp mypassword
schtasks.exe /tn Task2 /sd 2015-04-04  /ed 2015-05-05 /rp mypassword

I would like to know if i can use one line command to edit both tasks. Thank you for helping.

2 Answers 2

1

It's harder to make this a one liner when multiple pieces of information need to be changed. Lets try to pass an array of hash tables to Invoke-Expression

@(  @{Name = "Task1";StartDate = "2015-01-01";EndDate = "2015-02-02"},
    @{Name = "Task2";StartDate = "2015-04-04";EndDate = "2015-05-05"}
) | ForEach-Object{
    Invoke-Expression ("schtasks.exe /tn {0} /sd {1}  /ed {2} /rp mypassword" -f $_.Name, $_.StartDate, $_.EndDate)
}

If you had a CSV file with the columns Name, StartDate, EndDate then you could pipe that right into the ForEach we have there. That was you don't need to declare the array statically in the code.

Most PowerShell code can be written in one line. Just depends how horrible you expect it to look for the next person.

Sign up to request clarification or add additional context in comments.

4 Comments

Name and date also changes
@Redadublex yeah... that should have been obvious. It was late. I updated the code a little.
nice answer it's array or hash table ?
@SoheilHashemi its an array of hashtables :). It's set up that way so that we could use Import-CSV without changing the process code.
0

Script-like approach:

# Set password
$Password = 'Passw0rd'

# This is multidimensional array, i.e. an array that contains other arrays
# Each of those sub-arrays contains commandline parameters for schtasks.exe
$Commands = @(
    @('/tn', 'Task1', '/sd', '2015-01-01', '/ed', '2015-02-02', '/rp', $Password),
    @('/tn', 'Task2', '/sd', '2015-04-04', '/ed', '2015-05-05', '/rp', $Password)
)

# Iterate sub-arrays, and run schtasks.exe with commandline arguments from each
$Commands | ForEach-Object {& 'schtasks.exe' $_}

One-liner:

@('/tn', 'Task1', '/sd', '2015-01-01', '/ed', '2015-02-02', '/rp'), @('/tn', 'Task2', '/sd', '2015-04-04', '/ed', '2015-05-05', '/rp') | ForEach-Object {& 'schtasks.exe' ($_ + 'Passw0rd')}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.