powershell - 以多个用户身份运行Powershell脚本

标签 powershell active-directory wmi powershell-2.0

我的服务器管理员和工作站管理员角色有不同的帐户。我想运行一个Powershell脚本,该脚本将查询我的广告以获取计算机列表以及每台计算机返回的查询以检查服务。第一部分需要以服务器管理员身份运行,第二部分需要以工作站管理员身份运行。目前,我使用两个单独的脚本。是否可以将其集成到一个脚本中?

这是我的两个脚本,它们都在一台计算机上运行。我在工作站上运行但以服务器管理员帐户运行的第一个脚本,因为这是唯一可以访问 Activity 目录的脚本。该脚本创建第二个脚本使用的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"

脚本1
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

脚本2
$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"
    }
}

最佳答案

您可以循环浏览一系列计算机,并使用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"
    }
}

关于powershell - 以多个用户身份运行Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29805310/

相关文章:

java - LDAP 和 Java : how to check if PagedResultsControl and/or VLV are available

java - 校验和失败 : Kerberos/Spring/Active Directory (2008)

excel - Powershell:将粗体文本保存到变量中

windows - 使用 PowerShell 每 x 秒运行一次批处理文件

C# ActiveDirectory,如何将范围添加到过滤器

c# - 检测驱动器中 DVD 插入的最佳方法 C#

powershell - 为什么我不能从 WMI 中选择 AliasProperty?

python - 使用 Python 控制 Hyper-V 虚拟机

vba - 使用 PowerShell 发送击键并在文本中包含百分号

regex - 可选的非捕获组中的命名捕获组