簡體   English   中英

無法使用PowerShell在任務計划程序中創建任務

[英]Unable to create task in task scheduler using PowerShell

我正在嘗試使用Powershell在任務計划程序中創建任務。

$PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
3      0      -1     -1

操作系統:Windows Server 2012

這是供參考的腳本:

Set-Location c:\automation

# Remove IP of host on which this script is going to run
$hostname = hostname
$private_ip = (Test-Connection $hostname -count 1).IPv4Address.IPAddressToString
(get-content .\sch_task_action.conf) | foreach-object {$_ -replace "and not net $private_ip", ""} | set-content .\sch_task_action_final.conf

# Create task schedular
$sch_task_action = Get-Content c:\automation\sch_task_action_final.conf -Raw
$sch_task_principal = New-ScheduledTaskPrincipal -UserId "LOCALSERVICE" -LogonType ServiceAccount
$sch_task_settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Days 7)
$trigger = New-ScheduledTaskTrigger -AtStartup

Register-ScheduledTask -Action $sch_task_action -Trigger $trigger -Principal $sch_task_principal -Settings $sch_task_settings -TaskName "Monitoring"

sch_task_action.conf內容:

New-ScheduledTaskAction -Execute c:\windump\windump.exe –Argument "-i 1 -q -w e:\network-dump\Network-Traces.txt -n -C 100 -W 100 -U -n ip and not net 125.14.93.7 and not net 10.0.2.4"

當我嘗試運行PowerShell腳本時,出現以下錯誤:

Register-ScheduledTask : Cannot process argument transformation on parameter 'Action'.
Cannot convert value "New-ScheduledTaskAction -Execute C:\windump\windump.exe –Argument
"-i 1 -q -w E:\network-dump\Network-Traces.txt -n -C 100 -W 100 -U -n ip and not net
125.14.93.7 and not net 10.0.2.4"
" to type "Microsoft.Management.Infrastructure.CimInstance[]".
Error: "Cannot convert value "New-ScheduledTaskAction -Execute C:\windump\windump.exe
–Argument "-i 1 -q -w E:\network-dump\Network-Traces.txt -n -C 100 -W 100 -U -n ip and
not net 125.14.93.7 and not net 10.0.2.4"
" to type "Microsoft.Management.Infrastructure.CimInstance".
Error: "Specified argument was out of the range of valid values.
Parameter name: className""
At C:\Automation\windump\win_dump.ps1:26 char:32
+ Register-ScheduledTask -Action $sch_task_action -Trigger $trigger -Principal $sc ...
+                                ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Register-ScheduledTask], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Register-ScheduledTask

注意:在腳本中,如果我不使用Get-Content讀取文件而將sch_task_action_final.conf (已刪除選定IP)的內容直接傳遞到變量(如下所示),則腳本可以正常工作並創建任務在調度程序中。

$sch_task_action = New-ScheduledTaskAction -Execute c:\windump\windump.exe –Argument "-i 1 -q -w e:\network-dump\Network-Traces.txt -n -C 100 -W 100 -U -n ip and not net 125.14.93.7"

我花了幾個小時試圖通過在線搜索找出答案,但無濟於事。

Get-Content -Raw返回一個字符串,PowerShell不會解釋該字符串,並且不能按Get-Content -Raw將其傳遞給參數-Action 刪除New-ScheduledTaskAction -Execute-Argumentsch_task_action_final.conf和變化

$sch_task_action = Get-Content c:\automation\sch_task_action_final.conf -Raw

$action, $params = (Get-Content C:\automation\sch_task_action_final.conf -Raw) -split ' ', 2
$sch_task_action = New-ScheduledTaskAction -Execute $action -Arugment $params

或者,您可以使用Invoke-Expression

$sch_task_action = Invoke-Expresssion (Get-Content c:\automation\sch_task_action_final.conf -Raw)

但我不建議這樣做。

您可以使用COM-Object創建計划任務。 使用Schedule.Service ,可以創建它:

                $service = new-object -ComObject("Schedule.Service")
                # connect to the local machine.

                $service.Connect()
                $rootFolder = $service.GetFolder("\")
                $TaskDefinition = $service.NewTask(0)
                $TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
                $TaskDefinition.Settings.Enabled = $true
                $TaskDefinition.Settings.AllowDemandStart = $true
                $TaskDefinition.Settings.StartWhenAvailable = $true
                $TaskDefinition.Settings.StopIfGoingOnBatteries=$false
                $TaskDefinition.Settings.DisallowStartIfOnBatteries=$false
                $TaskDefinition.Settings.MultipleInstances=2
                $taskdefinition.Settings.WakeToRun=$true
                $triggers = $TaskDefinition.Triggers
                $trigger = $triggers.Create(1) # Creates a "One time" trigger
                $trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
                $time_interval=New-TimeSpan -Minutes $interval
                $time_interval=$time_interval.TotalSeconds
                $trigger.Repetition.Interval= "PT"+"$time_interval"+"S"
                $trigger.Enabled = $true
                $TaskDefinition.Principal.RunLevel =1
                $Action = $TaskDefinition.Actions.Create(0)
                $action.Path = "$TaskCommand"
                $action.Arguments = "$TaskArg"
                # In Task Definition,
                #   6 indicates "the task will not execute when it is registered unless a time-based trigger causes it to execute on registration."
                #   5 indicates "Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.In this case, its the SYSTEM"
                $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) | Out-Null
                "Scheduled Task has been created successfully"
                Write-Log -Message "Scheduled Task has been created successfully with the name SHA_$schedule_name" -Level Info

這是供您參考的鏈接: PS中的計划任務

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM