Hy, i try to use powershell to automate some scheduling tasks Should start a cmd.exe in a specific directory.
Unfortunately it returns an error on a specific property
Property: TaskName.Actions.WorkingDirectory
# Testprog for Scheduler working directory setup
cls
$TaskName = "TestTask"
# Helpers for Task creation comment out when task exist
UnRegister-ScheduledTask -TaskName $TaskName
$Description = " Test Powershell Task creation"
$Trigger= New-ScheduledTaskTrigger -Daily -At 02:00pm
$Action= New-ScheduledTaskAction -Execute cmd.exe -Argument $StartString
$ProgPath = """e:\Temp\Software\7zip\7za.exe"""
$Param = " a -t7z -bd -ssw -wE:\Temp"
$Archive = " ""E:\Temp\LocalArch\TestArch.7z"""
$SourcePath = " ""E:\Logs\"" "
$User= "NT AUTHORITY\SYSTEM"
$StartString = "/c " $ProgPath $Param $Archive $SourcePath
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force -Description $Description
#>
$Task = Get-ScheduledTask -TaskName $TaskName # Read Scheduler Task to Object
$Task.Actions.WorkingDirectory # Retrieve no error
# E:\WrittenViaGUI # Test return value written via schduler GUI
$Task.Actions.WorkingDirectory = "E:\Temp\" #New working dir
Error: The property 'WorkingDirectory' cannot be found on this object.
CodePudding user response:
As the name of the property suggests, $Task.Actions
contains a collection of values (even if in a given situation that collection contains just one element).
PowerShell's member enumeration feature allows you to use property access (.WorkingDirectory
) on a collection to get the property values of its elements - that is why $Task.Actions.WorkingDirectory
succeeded - but not also to set property values - that is why $Task.Actions.WorkingDirectory = ...
failed.
You solution options are:
If you know that
.Actions
contains only one action, simply use[0]
to access the one and only element:$Task.Actions[0].WorkingDirectory = 'E:\Temp\'
If
.Actions
contains multiple actions, and you want to set all their working directories to the same value:$Task.Actions.ForEach('WorkingDirectory', 'E:\Temp\') # Slower alternatives $Task.Actions.ForEach({ $_.WorkingDirectory = 'E:\Temp\' }) $Task.Actions | ForEach-Object { $_.WorkingDirectory = 'E:\Temp\' }
For more information, see this answer.