简体   繁体   English

读取csv文件以使用Powershell和Task Scheduler COM-Object创建从事件ID触发的任务

[英]Read csv file to create tasks that trigger from an event id using powershell and Task Scheduler COM-Object

I created a CSV File that looks like this 我创建了一个看起来像这样的CSV文件

sequence,reportsource,reportname,reportid,fullpath 序列,报告源,报告名称,报告ID,完整路径

It contains several lines of configuration data for the scheduled tasks. 它包含计划任务的几行配置数据。 I already figured out to use import-csv to get the content of the file. 我已经想通了使用import-csv来获取文件的内容。 Now I want to loop through every line of the file and store all the values of the line to variables - collection ($sequence,$reportsource,$reportname,$reportid,$fullpath), so I can create scheduled tasks with this values, but I don't know how to access the object, that import-csv provides. 现在,我想遍历文件的每一行,并将该行的所有值存储到变量中-集合($ sequence,$ reportsource,$ reportname,$ reportid,$ fullpath),以便可以使用此值创建计划任务,但我不知道import-csv提供的如何访问对象。 I need those values from the csv to hand over arguments to schtasks.exe to create my tasks. 我需要csv中的这些值来将参数移交给schtasks.exe来创建我的任务。

$path = "C:\Workspace\macros\FullReportPathMR.csv"
$PSVersionTable.PSVersion

$csv = Import-CSV -Path $path -Delimiter ";" | %{

##SCHTASKS /Create /TN $($_.reportname) /sc monthly /tr "C:\Program Files (x86)\Microsoft Office###\Office14\EXCEL.EXE"
#New-ScheduledTaskAction -Execute "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" -Argument #"$($_.fullpath)"
#}

# The name of the scheduled task
[string]$TaskName = "$($_.reportsource) - $($_.reportname) - $($_.reportid)"
# The description of the task
[string]$TaskDescr = "Hello, it's you again! I am $($_.reportname) and I will get started, when Report ID $($_.reportid) is fired. Have a nice day!"
# The Task Action command
$TaskCommand0 = "kill.cmd"
$TaskCommand1 = "`"C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE`""

# The Task Action command argument
$TaskArg = "hallelujah"
$TaskArg1 = "$($_.fullpath)"
# attach the Task Scheduler com object
$service = new-object -ComObject("Schedule.Service")
# connect to the local machine. 
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx
$service.Connect()
$rootFolder = $service.GetFolder("\")

$TaskDefinition = $service.NewTask(0) 
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true

$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(0) # Creates an "On an event" trigger
$trigger.Subscription = "<QueryList><Query Id='0'><Select Path='Application'>*[System[Provider[@Name='$($_.reportsource)'] and EventID='$($_.reportid)']]</Select></Query></QueryList>"

# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand0"
$action.Arguments = "$TaskArg"
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand1"
$action.Arguments = "$TaskArg1"

#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx
$rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5)

Write-Host $($_.sequence) $($_.reportsource) $($_.reportname) $($_.reportid) $($_.fullpath) "task created successfully."

}

CSV File Contains CSV文件包含

sequence;reportsource;reportname;reportid;fullpath
1;Monthly Report;MR1;3;C:\Workspace\macros\1.txt
2;Monthly Report;MR2;6;C:\Workspace\macros\2.txt
3;Monthly Report;MR3;9;C:\Workspace\macros\3.txt
4;Monthly Report;MR4;12;C:\Workspace\macros\4.txt

https://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/ https://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/

https://community.spiceworks.com/topic/1028906-trigger-schedule-task-on-an-eventid https://community.spiceworks.com/topic/1028906-trigger-schedule-task-on-an-eventid

https://powershell.org/forums/topic/scheduled-task-with-multiple-actions/ https://powershell.org/forums/topic/scheduled-task-with-multiple-actions/

The whole thing ran through on a Windows 7 with PS 2.0.-1.-1 administration machine and created 4 tasks with the desired parameters and arguments. 整个过程在带有PS 2.0.-1.-1管理机的Windows 7上运行,并创建了4个具有所需参数和参数的任务。 The subscription - thing is a bit tricky, since I can't manipulate the event trigger using the GUI, just editing the XML. 订阅-事情有点棘手,因为我无法使用GUI来操纵事件触发器,只能编辑XML。 Every task provides 2 actions. 每个任务提供2个动作。

OK the question looks like it could just be simply 好了,问题看起来可能仅仅是

"How do I store the values of a CSV in a variable and loop through them?" “如何将CSV的值存储在变量中并遍历它们?”

Lets go over some basic Powershell concepts to understand what you should be looking for. 让我们研究一些基本的Powershell概念,以了解您应该寻找的内容。

The solution is. 解决的办法是。

Import-Csv -Path "C:\Test.csv" | %{
    Put Code Here
}

Ok lets explain this. 好,让我们解释一下。

Lets image we have a csv called test.csv and the inside looks like 让我们有一个名为test.csv的csv,内部看起来像

"FirstName","LastName","Age" "Bill","Boxer","52" "Steve","Nix","21"

When I call Import-CSV it creates a PSObject with properties that are equal to the header (First line of the CSV) : 当我调用Import-CSV时,它将创建一个PSObject,其属性等于标题(CSV的第一行):

(Import-csv "C:\Test.csv").FirstName

will return 将返回

Bill Steve

In powershell we love piping | 在Powershell中,我们喜欢管道| What this does is takes the information for the previous command and moves it to the next command using $_ as the variable. 这样做是使用$ _作为变量将上一条命令的信息移到下一条命令。 We also love shorthand known as Alias. 我们也喜欢被称为Alias的速记。 Like %{ Code Here } is short hand for foreach-object %{ Code Here }foreach-object简写

so 所以

Import-csv "C:\Test.csv" | %{
    "My Name Is $($_.FirstName) $($_.LastName) and I am $($_.Age) years old"
}

Will get the data from the CSV and convert it to a PSObject. 从CSV获取数据并将其转换为PSObject。 It will then Pipe | 然后它将管道| to a Foreach-Object aka %{} and then display the string : 到一个Foreach-Object aka %{} ,然后显示字符串:

My Name Is Bill Boxer and I am 52 years old My Name Is Steve Nix and I am 21 years old

On a side note the $() inside the quotes is called a expression "$(Code here)" Allows you to output the code inside of a string 附带说明一下,引号内的$()称为表达式“ $(此处为代码)”,允许您在字符串内部输出代码

"Hello $_.FirstName"

Would show everything in the variable $_ then add a .FirstName to the end of it like : 将在变量$ _中显示所有内容,然后在其末尾添加.FirstName,例如:

@{FirstName=Bill; LastName=Boxer; Age=52}.FirstName

But when you add the $() expression you are saying run this part as code. 但是,当您添加$()表达式时,您要说的是将此部分作为代码运行。

"Hello $($_.FirstName)"

Shows 演出

Hello Bill

So lets take a look at the code you posted in the comments (Please keep in mind to edit your post and post it there for other people to read. 因此,让我们看一下您在评论中发布的代码(请记住编辑您的帖子并将其发布在此处,以供其他人阅读。

Based on what I have posted above the issue is that your CSV isnt a CSV. 根据我上面发布的内容,问题是您的CSV不是CSV。 CSV stands for Comma Separated Value. CSV代表逗号分隔值。 You have your values separated by Semi Colons. 您的价值观之间用半冒号隔开。

You will need to define that in the Param for import-Csv -Delimiter ";" 您将需要在import-Csv -Delimiter ";"的参数中定义它import-Csv -Delimiter ";"

A working script would be this : 一个有效的脚本是这样的:

$path = "C:\Workspace\macros\FullReportPathMR.csv"
Import-CSV -Path $path -Delimiter ";" | %{
    "$($_.sequence) $($_.reportsource) $($_.reportname) $($_.reportid) $($_.fullpath)"
}

output 输出

1 Monthly Report MR1 3 C:\\Workspace\\macros\\1.txt 2 Monthly Report MR2 6 C:\\Workspace\\macros\\2.txt 3 Monthly Report MR3 9 C:\\Workspace\\macros\\3.txt 4 Monthly Report MR4 12 C:\\Workspace\\macros\\4.txt

The code below will load a CSV where the code is located. 下面的代码将在代码所在的位置加载CSV。
Than it will loop inside of the file and create a schedule task. 然后它将在文件内部循环并创建计划任务。
This script requires admin rights to create a new scheduled task and it will create a task as the current user. 该脚本需要管理员权限才能创建新的计划任务,它将以当前用户身份创建任务。

# get scripth path location
$scriptpath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

# import CSV
$csvdata = Import-Csv "$scriptpath\t.csv"

# this will clycle throught the data inside the object $csvdata
foreach ($result in $csvdata) {
    # to access the data just refer to object $result.[columns names inside CSV]

    # Build task info
    $action  = New-ScheduledTaskAction -Execute "$($result.fullpath)" -Argument 'case there is any argument'
    $trigger = New-ScheduledTaskTrigger -Daily -At 9am 
    Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $($result.reportname) -Description $($result.reportname)
    # create the task scheduler
    New-ScheduledTaskAction -Execute 
}

The task creation part was base on: https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/13/use-powershell-to-create-scheduled-tasks/ 任务创建部分基于以下内容: https//blogs.technet.microsoft.com/heyscriptingguy/2015/01/13/use-powershell-to-create-scheduled-tasks/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM