使用web客户端,Windows服务器常用的自动化脚本

以下是批量Windows服务器安装谷歌流量器

ChromeSetup.exe为已经下载好的谷歌浏览器安装文件,serverlist.txt为服务器IP列表文件,<username> <password>替换为服务器账号密码,创建计划任务执行。

#!/bin/bash

username="<username>"
password="<password>"
installer="ChromeSetup.exe"

while read -r server; do
  pwsh -Command "
    $username = '$username'
    $password = '$password' | ConvertTo-SecureString -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($username, $password)
    Invoke-Command -ComputerName \\$server -Credential $credential -ScriptBlock {
      Start-Process msiexec.exe -ArgumentList '/i', '$env:installer', '/quiet', '/norestart' -Wait
    }
  "
done < serverlist.txt

echo "All done!"
当我们的软件并未下载到网关服务器的时候,就需要使用URL下载模式执行安装
<download_url>改为软件下载链接,必须是绝对下载地址,如:https://web.danny.fund/ChromeSetup.exe


#!/bin/bash
username="<username>"
password="<password>"
url="<download_url>"

while read -r server; do
  pwsh -Command "
    $username = '$username'
    $password = '$password' | ConvertTo-SecureString -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($username, $password)
    Invoke-Command -ComputerName \\$server -Credential $credential -ScriptBlock {
      $client = New-Object System.Net.WebClient
      $client.DownloadFile('$env:url', 'installer.msi')
      Start-Process msiexec.exe -ArgumentList '/i', 'ChromeSetup.exe', '/quiet', '/norestart' -Wait
    }
  "
done < serverlist.txt

echo "All done!"

当我们需要对没有导入到客户端的Windows服务器批量重启时,可以创建计划并使用以下代码实现批量重启

#!/bin/bash

username="<username>"
password="<password>"

while read -r server; do
  pwsh -Command "
    $username = '$username'
    $password = '$password' | ConvertTo-SecureString -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($username, $password)
    Invoke-Command -ComputerName \\$server -Credential $credential -ScriptBlock {
      Restart-Computer
    }
  "
done < serverlist.txt

echo "All done!"

批量修改Windows实例密码,当我们已经导入服务器到资产中时,自动计划代码如下:

userName为账号(默认为administrator)newPassword为修改后新密码

$userName="{{userName}}"
$newPassword="{{newPassword}}"

$UserAccountInfo=Get-WmiObject -Class Win32_UserAccount -Filter "Name='$userName'" | Select Name,Status,Disabled,Lockout,LocalAccount,PasswordExpires,PasswordChangeable,AccountType

if ($UserAccountInfo.Disabled -eq "True") {
    Write-Host -ForegroundColor Yellow "$userName account has been disabled. Now active it."
    net user $userName /active:yes |Out-Null
}

if ($UserAccountInfo.Lockout -eq "True") {
    Write-Host -ForegroundColor Yellow "$userName account has been locked. Now active it."
    net user $userName /active:yes |Out-Null
}

net user $userName $newPassword