我的服务器管理员和工作站管理员角色有不同的帐户。我想运行一个powershell脚本来查询我的广告,以获取计算机列表以及每台计算机返回的查询以检查服务。第一部分需要作为服务器管理员运行,第二部分需要作为工作站管理员运行。目前我使用两个单独的脚本。是否可以将其集成到一个脚本中?
这是我的两个脚本,它们都在一台计算机上运行。我在我的工作站上运行的第一个脚本,但作为我的服务器管理员帐户运行,因为这是唯一可以访问活动目录的脚本。此脚本创建第二个脚本使用的XML文件。我将此脚本作为我的工作站管理员帐户运行。
runas.exe /user:domain\srvadmin "powershell.exe -executionpolicy bypass -command c:\output\script1.ps1"
runas.exe /user:domain\wsadmin "powershell.exe -executionpolicy bypass -command c:\output\script2.ps1"
SCRIPT1
import-module -name activedirectory -cmdlet get-adcomputer, get-adorganizationalunit;
$orgUnit = @("OU=Computers,DC=domain,DC=com")
$computerList = get-adcomputer -filter * -searchscope subtree -searchbase (get-adorganizationalunit $orgUnit).distinguishedname;
write $computerList | export-clixml c:\output\computerList.xml
SCRIPT2
$computersInOU = import-clixml c:\output\computerList.xml
foreach ($comp in $computersInOU) {
if ($comp.Enabled) {
$cpu = get-wmiobject -class win32_processor -computername $comp.name
write "$comp.name $cpu"
}
}
答案 0 :(得分:1)
您可以遍历一系列计算机并使用Invoke-Command
远程运行脚本:
$script = {Get-Process explorer}
$servers = @("Server1", "Server2") # or $servers = Get-ADComputer -filter blah1
$serverCred = Get-Credential "(Server)"
$workstations = @("WS1", "WS2") # or $workstations = Get-ADComputer -filter blah2
$workstationCred = Get-Credential "(Workstation)"
$servers | %{Invoke-Command $script -Computer $_ -Credential $serverCred}
$workstations | %{Invoke-Command $script -Computer $_ -Credential $workstationCred}
根据新的问题信息进行更新:
您可以像这样组合脚本:
$srvCred = Get-Credential "domain\srvadmin"
$wsCred = Get-Credential "domain\wsadmin"
Import-Module -name ActiveDirectory -cmdlet Get-ADComputer, Get-ADOrganizationalUnit;
$orgUnit = @("OU=Computers,DC=domain,DC=com")
$searchBase = (Get-ADOrganizationalUnit -Credential $srvCred $orgUnit).distinguishedname
$computersInOU = Get-ADComputer -Credential $srvCred -filter * -searchscope subtree -searchbase $searchBase;
foreach ($comp in $computersInOU) {
if ($comp.Enabled) {
$cpu = Get-WmiObject -Credential $wsCred -class win32_processor -computername $comp.name
write "$comp.name $cpu"
}
}