【问题标题】:Powershell run command against each item in text filePowershell 针对文本文件中的每个项目运行命令
【发布时间】:2016-10-27 21:01:03
【问题描述】:

发现我最初发布的脚本最初存在问题。这是下一期,我相信这很容易。

以下脚本的目标是针对在主机名列表文本文件中找到的每台计算机运行指定的 ADSI 命令——示例如下:

电脑01

电脑02

电脑03

问题在于,在运行脚本时,它会获取计算机名称文件中的每个计算机名称并将它们混合在一起以形成一个巨大的计算机名称,这显然不是我要连接的计算机!

这是脚本。我试图运行的 ADSI 函数大约下降了 3/4。

Function Get-OpenFile($initialDirectory)
{ 
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Text Files (*.txt)|*.txt)|CSV Files (*.csv)|*.csv)"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
$OpenFileDialog.ShowHelp = $true
}

$InputFile = Get-OpenFile
$Computers = get-content -path $InputFile

Do {
write-host = "Do you want to Enter a Domain Group to Add to the Local Administrators Group?  Type Y for Yes, or N for No"
$GroupAddOperation = read-host = " "
If ($GroupAddOperation -eq "N") {break}

Do {
write-host = "Enter Group Name"
$groupname = Read-Host " "

$DomainGroup = $groupname
$LocalGroup  = "Administrators"
$Domain      = "domainname.com"
$pc          = $computers

([ADSI]"WinNT://$pc/$LocalGroup,group").psbase.Invoke("Add",([ADSI]"WinNT://$Domain/$DomainGroup").path)

Write-Host "Do you want to Add Another Group? Enter Y for Yes or N for No"
$AddAnotherGroup = Read-Host " "
}
Until ($AddAnotherGroup -eq "N")
}
Until ($GroupAddOperation -eq "N")

如果我运行带有“Write-Host”命令的 ADSI 命令,PS 控制台的输出如下:

([ADSI] WinNT://Computer01.domainname.com Computer02.domainname.com Computer03.domainname.com/Administrators group).psbase.Invoke(Add,([ADSI]WinNT://us.kworld.kpmg.com/us-sg eaudit business).p
ath)

基本上我需要的是在所有三台计算机上按顺序运行 ADSI 命令。我做错了什么?

【问题讨论】:

标签: powershell adsi


【解决方案1】:

作为 TessalatingHeckler 链接到的。 从文件或哈希表​​中获取您的计算机并将它们分配给一个变量。

$computers = @("Computer01", "Computer02", "Computer03")

foreach($computer in $computers)
    {
    ([ADSI]"WinNT://$computer/$LocalGroup,group").psbase.Invoke("Add",([ADSI]"WinNT://$Domain/$DomainGroup").path)
    }

希望这会有所帮助。

【讨论】:

  • 非常感谢,这非常有效。我所做的是将@() 运算符添加到包含使用文件对话框函数提取的信息的变量中。一旦定义好,我就可以将命令单独应用于每台计算机!我将在另一篇文章中显示固定代码!
  • 很高兴知道它有效,感谢您告诉我们。
猜你喜欢
  • 2013-04-21
  • 1970-01-01
  • 2012-12-23
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
  • 2015-09-02
  • 2021-05-07
相关资源
最近更新 更多