简体   繁体   中英

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.

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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