我想在服务器上使用Powershell创建几个计划任务。我已经从现有的时间表
创建了该文件我已经加载了csv文件,将其传送到select,并从csv文件中检索了我需要的所有信息。但是我不确定如何将这些结果传递给外部非powershell命令。
Import-Csv .\listoftasks.csv | Select 'Run As User','RP','Scheduled Type','TaskName','Task To Run','Repeat: Every','Repeat: Until: Duration'
我想做的是:
Import-Csv .\listoftasks.csv | Select 'Run As User','RP','Scheduled Type','TaskName','Task To Run','Repeat: Every','Repeat: Until: Duration' | schtasks /create /RU ....
答案 0 :(得分:4)
尝试使用ForEach-Object
:
Import-Csv .\listoftasks.csv |
Select-Object 'Run As User','RP','Scheduled Type','TaskName','Task To Run','Repeat: Every','Repeat: Until: Duration' |
ForEach-Object { Invoke-Expression "schtasks /create /RU ..." }
另外,要注意名称中包含空格的属性。如果名称包含空格,您可以像这样访问它们:
$_.'Run As User'
答案 1 :(得分:4)
发布我收到的建议的最终结果,希望其他人也可以使用它。 :)
#Added a column to the csv with heading RP - contains the password if you have to use
#hardcoded account \ passwords and cant use the system accounts
$ListOfTasks = Import-Csv ListOfTasksExport.csv | Select
'Run As User' `
,'RP' `
,'Scheduled Type' `
,'TaskName' `
,'Task To Run' `
,'Repeat: Every' `
,'Repeat: Until: Duration' `
,'Start Time' `
, 'HostName'
ForEach($item in $ListOfTasks)
{
$dateOfItem = [DateTime]::Parse($item.'Start Time')
$stringOfDateOfItem = $dateOfItem.ToString("HH:mm")
$tr = $item.'Task To Run'
$user = $item.'Run as User'
$UserPassword = $item.'RP'
$scheduledType = $item.'Scheduled Type'
$taskName = $item.'TaskName'
$taskToRun = $item.'Task To Run'
$hostName = $item.'HostName'
$serviceAccount = 'domain\serviceAccount'
$serviceAccountPassword = 'HardCodedPassword'
#Debugging
#Write-Host -BackgroundColor yellow $taskName
#Write-Host $stringOfDateOfItem
#Write-Host $tr
#Write-Host $user
#Write-Host $UserPassword
#Write-Host $scheduledType
#Write-Host $taskName
#Write-Host $taskToRun
#Checks if the user is nt authority, it does not put the password field in
if($env:computername.Contains($hostName))
{
if($user.Contains("NT AUTHORITY"))
{
schtasks /create /RU $user /SC $scheduledType /TN $taskName /TR $taskToRun /ST $stringOfDateOfItem /F
}
else
{
schtasks /create /RU $user /RP $UserPassword /SC $scheduledType /TN $taskName /TR $taskToRun /ST $stringOfDateOfItem /F
}
}
else
{
if($user.Contains("NT AUTHORITY"))
{
schtasks /create /s $hostName /U $serviceAccount /P $serviceAccountPassword /RU $user /SC $scheduledType /TN $taskName /TR $taskToRun /ST $stringOfDateOfItem /F
}
else
{
schtasks /create /s $hostName /U $serviceAccount /P $serviceAccountPassword /RU $user /RP $UserPassword /SC $scheduledType /TN $taskName /TR $taskToRun /ST $stringOfDateOfItem /F
}
}
}