简体   繁体   English

使用 Powershell 创建任务

[英]Create A Task Using Powershell

Good Afternoon:下午好:

I have written a PS Script that can create a task on my local machine;我写了一个可以在本地机器上创建任务的PS脚本; however, it is my intention to have this configure a task on multiple machines from a list.但是,我打算让这个在列表中的多台机器上配置一个任务。 I cannot seem to find a way on how to do this.我似乎无法找到如何做到这一点的方法。 I did see something on using New-CimSession, but I dont think that is what I am looking for...我确实看到了一些关于使用 New-CimSession 的内容,但我认为这不是我要寻找的......

Here is my script:这是我的脚本:


foreach ($confighost in (Get-Content -Path "C:\Users\*User*\Documents\Test.txt"))
{
#Check for existent script in Task Scheduler

$taskpath = "\\$confighost\c$\Windows\System32\Tasks\LocalUserCleanUp"
$testtask = Test-Path -path $taskpath

If ($testtask -eq $true)
    {

        #If Task is already present, Do Not Run

        Write-Host "CleanUp Task Listed in Task Scheduler On" $confighost ". Will not Implement Task..."

    }

else
    {

        #If Task Does Not Exist Create Task
        New-CimSession -ComputerName $confighost
        Write-Host "No CleanUp Task Listed in Task Scheduler, Creating Task..."
        $action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "C:\Users\*Users*\Documents\ProfileCleanup.ps1"
        $trigger = New-ScheduledTaskTrigger -Daily  -At 2am
        $settings = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
        Register-ScheduledTask -Action $action -Trigger $trigger -Principal $settings -TaskName "LocalUserCleanUp" -Description "Checks user accounts nightly to see if they are older than 30 days"

    }
} 

I look forward to your insight.我期待你的洞察力。 Thanks again for all your assistance!再次感谢您的帮助!

You can use Invoke-Command to execute your task creation code on a target server:您可以使用Invoke-Command在目标服务器上执行您的任务创建代码:

$cred = Get-Credential # There are a number of methods to automate reading the credential from a file
Invoke-Command -Credential $cred -ComputerName server01, server02, server0X {
  # Your task creation code here
}

If you have any variables defined in your local session that you need available in the remote code, you can reference them in your Invoke-Command ScriptBlock reference the variable from the using scope by prefixing the local variable with $using: .如果您在本地会话中定义了任何需要在远程代码中可用的变量,您可以在您的Invoke-Command ScriptBlock引用它们,通过在本地变量前加上$using: usingusing范围引用变量。

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

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