尝试使用powershell从AD安全组中删除计算机对象并从CSV文件导入

zi8p0yeb  于 2022-12-06  发布在  Shell
关注(0)|答案(1)|浏览(129)

我对这个很感兴趣。另外,我想在这个开头加上一句,我不是PowerShell方面的佼佼者,因为我才刚刚开始。我有一个CSV文件,我正在尝试读取第一列,碰巧是“AssetName”。这些是加入AD的计算机。

#Get Computer
$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv'  | Select-Object AssetName
$Group = "Sec Group Name"

# Set the ErrorActionPreference to SilentlyContinue, because the -ErrorAction 
# option doesn't work with Get-ADComputer or Get-ADGroup.
$ErrorActionPreference = "SilentlyContinue"

# Get the computer and group from AD to make sure they are valid.
$ComputerObject = Get-ADComputer $Computer
$GroupObject = Get-ADGroup $Group

Foreach ($Computer in $Computers){
    if ($GroupObject) {
        # If both the computer and the group exist, remove the computer from 
        # the group.
        Remove-ADGroupMember $Group `
            -Members (Get-ADComputer $Computer).DistinguishedName -Confirm:$False
        Write-Host " "
        Write-Host "The computer, ""$Computer"", has been removed from the group, ""$Group""." `
            -ForegroundColor Yellow
        Write-Host " "
    }
    else {
        Write-Host " "
        Write-Host "I could not find the group, ""$Group"", in Active Directory." `
            -ForegroundColor Red
        Write-Host " "
    }
}
else {
    Write-Host " "
    Write-Host "I could not find the computer, $Computer, in Active Directory." `
        -ForegroundColor Red
    Write-Host " "
}

在执行此操作后,我希望从特定安全组中删除该资产。每当我运行脚本时,我都会收到此错误。我不知道为什么它使用“@{AssetName=CompName}"阅读它。
计算机“@{AssetName=CompName}"已从组“Sec Group Name”中删除。
任何帮助都将不胜感激。

chy5wohz

chy5wohz1#

第一行是将PSObject列表保存到$Computers。

$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv'  | Select-Object AssetName

这些对象看起来像@{AssetName=Computername}
迭代这些对象时,需要指定仅需要AssetName参数的值

Get-ADComputer $Computer.AssetName

另一种(在我看来更好的)方法是停止使用Select-Object(它将返回的对象存储在$computers中),只在$computers中存储一个AssetName列表,如下所示:

$Computers = (Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv').AssetName

编辑:
您也可以将-ExpandProperty与Select-Object一起使用:

$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv'  | Select-Object -ExpandProperty AssetName

相关问题