I have different accounts for my server admin and workstation admin roles. I want to run a powershell script that will query my ad to get a list of computers and the query each computer returned to check for a service. The first part needs to run as the server admin and the second as the workstation admin. Currently I use two separate scripts. Is it possible to integrate it into one script?
Here are my two scripts they both run on the one computer. The first script I run on my workstation but run as my server admin account as this is the only one with access to active directory. This script creates an XML file which is used by the second script. I run this script as my workstation admin account.
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"
}
}
You can cycle through an array of machines and use Invoke-Command
to run scripts remotely:
$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}
Update based on new question info:
You can combine your scripts like this:
$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"
}
}