简体   繁体   English

如何将PowerShell脚本推送到域计算机?

[英]How do I push a PowerShell script out to domain computers?

I am trying to run a command that will add a local administrator onto computers. 我正在尝试运行将本地管理员添加到计算机上的命令。 However, I am struggling to combine it with a script to push this out to all domain computers under a particular OU in Active Directory. 但是,我正在努力将其与脚本结合使用,以将其推送到Active Directory中特定OU下的所有域计算机。

Below is the first bit of script is the command I'm using to create the user. 以下是脚本的第一部分,即我用来创建用户的命令。

I also have a script to pull all the required OU computers into a CSV, but I need to then push the below script to the PCs in this CSV. 我还有一个脚本将所有必需的OU计算机拉入CSV,但是我需要将以下脚本推入此CSV的PC中。 Is this possible? 这可能吗? I only want it to run the once, not as a start up script as I don't want it to create multiple users. 我只希望它运行一次,而不是作为启动脚本运行,因为我不希望它创建多个用户。

$Username = "user"
$Password = "Password"
$group = "Administrators"
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$existing = $adsi.Children | where {
    $_.SchemaClassName -eq 'user' -and $_.Name -eq $Username
}

if ($existing -eq $null) {
    Write-Host "Creating new local user $Username."
    & NET USER $Username $Password /add /y /expires:never

    Write-Host "Adding local user $Username to $group."
    & NET LOCALGROUP $group $Username /add
}

Write-Host "Ensuring password for $Username never expires."
& WMIC USERACCOUNT WHERE "Name='$Username'" SET PasswordExpires=FALSE

If you really want to run your script only once on each computer, all of the computers are powered on and PowerShell remoting is activated, you could do it like this: 如果您确实只想在每台计算机上运行脚本一次,并且所有计算机都已打开电源并且PowerShell远程处理已激活,则可以执行以下操作:

Get-ADComputer -Filter * -SearchBase "OU=myOU,DC=mydomain,DC=tld" | foreach {

    Invoke-Command -ComputerName $_.DNSHostname -ScriptBlock {

        # Your script goes here...
    }
}

The example above reads all computer objects from a predefined OU from Active Directory, connects to every one and executes your script (or anything in the -Scriptblock {} ) on the computer. 上面的示例从Active Directory的预定义OU中读取所有计算机对象,连接到每个对象,然后在计算机上执行脚本(或-Scriptblock {}中的任何内容)。

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

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