【问题标题】:Powershell script to audit hosts file on all hosts on a domain but doing OU by OU用于审核域上所有主机上的主机文件但按 OU 执行 OU 的 Powershell 脚本
【发布时间】:2016-03-09 11:04:45
【问题描述】:

我是 Powershell 的新手,我的任务是编写一个脚本,该脚本将从我域中每台 PC 和服务器中的每个主机文件中获取内容,但能够在 AD 中的每个 OU 上独立运行它。然后我需要输出到单个.csv 文件,其中包含每个主机的计算机名、IP 和内容。

谁能给点建议?

我想出了 2 行名为 GetHostInfo 来获取内容并写入单个 .csv 文件,但这与需要的内容相去甚远。我知道我可以强制脚本在每个单独的 OU 上运行,但不知道如何布局并将每个脚本报告回单个文档

Set-ExecutionPolicy unrestricted $env:computername Copy-Item C:\Windows\System32\drivers\etc\hosts C:\hosts\$env:computername.csv

我对这个脚本是否正确,它应该运行我在名为CH0DC01 的 DC 上发布的名为 GetHostInfo 的上述脚本,在 OU GG Workstation 上的域 gelbergroup.com

Import-module activedirectory 

$C=get-adcomputer -filter * -searchbase "ou=GG Workstation, dc=CH0DC01, dc=gelbergroup.com"| ForEach-Object {$_.Name} 

Invoke-command -computername $C -scriptblock {GetHostInfo}

如果是这样,我需要在哪里保存 GetHostInfo 脚​​本。我很困惑,因为我没有在脚本中给它一个在 OU 上运行它的路径。

【问题讨论】:

  • 欢迎来到 SO。请向我们展示您的尝试。 SO 不是在代码编写服务中。
  • 我想出了 2 行来获取内容并写入单个 .csv,但这与所需的内容相去甚远。我知道我可以强制脚本在每个单独的 OU 上运行,但不知道如何布置它并将每个脚本报告回单个文档 Set-ExecutionPolicy unrestricted $env:computername Copy-Item C:\Windows\System32\drivers\etc \hosts C:\hosts\$env:computername.csv
  • 请将您的代码编辑到您的问题中,而不是将其发布为 cmets。
  • 完成 - 这里是新手。感谢您的耐心等待

标签: powershell scripting


【解决方案1】:

示例 1:

# declare the Get-HostInfo function as follows
function Get-HostInfo {
    Set-ExecutionPolicy Unrestricted
    "$env:computername"
    Copy-Item "C:\Windows\System32\drivers\etc\hosts" "C:\hosts\$env:computername.csv"
}

# and then use it
Import-module ActiveDirectory

$searchBase = "ou=GG Workstation, dc=CH0DC01, dc=gelbergroup.com"

$computers = Get-ADComputer -Filter * -SearchBase $searchBase |
    ForEach-Object { $_.Name }

Invoke-Command -ComputerName $computers -ScriptBlock { Get-HostInfo }

示例 2:

# if you declare the Get-HostInfo function in another file,
# for example C:\scripts\functions.ps1, you can include it as follows
# this is called "dot-sourcing"

. "C:\scripts\functions.ps1"

Import-module ActiveDirectory

$searchBase = "ou=GG Workstation, dc=CH0DC01, dc=gelbergroup.com"

$computers = Get-ADComputer -Filter * -SearchBase $searchBase |
    ForEach-Object { $_.Name }

Invoke-Command -ComputerName $computers -ScriptBlock { Get-HostInfo }

更多关于点源的信息:http://ss64.com/ps/source.html

【讨论】:

  • 非常感谢您的回复。
  • 不客气。如果愿意,您可以点击投票下方的绿色对勾来接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多