我试图从CSV文件中禁用PC,但是我一直收到以下错误。
当我手动将设备列表复制到文本文件(记事本)时,代码可以正常工作
谢谢
Get-ADComputer:找不到具有身份的对象:' PC-125632' 在:< DC = XXX,DC = XXX,DC = XXX'。在行:12 char:15 + $ ADComputer = Get-ADComputer $ Computer -Properties Description +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
这是我到目前为止所尝试的
Get-Content C:\Temp\test.csv | Select-Object -Skip 1 | Set-Content C:\Temp\List.txt
$Computers = Get-Content C:\Temp\List.txt
Start-Sleep -s 5
ForEach ($Computer in $Computers)
{
$ADComputer = $null
$ADComputer = Get-ADComputer $Computer -Properties Description
If ($ADComputer)
{
Add-Content c:\temp\computers.log -Value "The following PC $Computer has been found and disabled"
Set-ADComputer $ADComputer -Description "$($ADComputer.Description)- Disable due to inactivity - $(Get-Date) - by $env:UserName " -Enabled $False
}
Else
{
Add-Content c:\temp\computers.log -Value "$Computer not Found in Active Directory or Was disabled before"
}
}
答案 0 :(得分:2)
错误消息确实显示了问题,但它非常微妙......有一个尾随空格(最后是计算机名称):
' PC-125632'
当计算机名称不应包括在内时,它将作为计算机名称的一部分。
使用Trim()
删除任何前导或尾随空格很容易解决。
我也按照我之前的评论使用Import-Csv
,-Filter "Name -eq $Computer"
因为没有匹配就会返回null。
$Computers = Import-Csv C:\temp\test.csv
Foreach ($Computer in $Computers.DeviceName) {
$Computer = $Computer.Trim()
$ADComputer = Get-ADComputer -Filter "Name -eq $Computer" -Properties Description
If ($ADComputer) {
Add-Content c:\temp\computers.log -Value "The following PC $Computer has been found and disabled"
Set-ADComputer $ADComputer -Description "$($ADComputer.Description)- Disable due to inactivity - $(Get-Date) - by $env:UserName " -Enabled $False
}
Else {
Add-Content c:\temp\computers.log -Value "$Computer not Found in Active Directory or Was disabled before"
}
}
答案 1 :(得分:0)
Get-ADComputer:找不到具有身份的对象:' PC-125632' 在:< DC = XXX,DC = XXX,DC = XXX'。在行:12 char:15 + $ ADComputer = Get-ADComputer $ Computer -Properties Description +
以上错误由(2)和(3)
纠正下面的代码我已经成功执行了。它工作正常..
(1)我改变了导入csv的方式。
$computers=Import-Csv -Path "C:\Temp\test.csv"
(2)而不是
ForEach ($Computer in $Computers)
我用
ForEach ($Computer in $Computers.distinguishedName)
休息是一样的..
总的来说,它看起来像这样,
$computers=Import-Csv -Path "C:\Temp\test.csv"
ForEach ($Computer in $Computers.distinguishedName)
{
$ADComputer = $null
$ADComputer = Get-ADComputer $Computer -Properties Description
If ($ADComputer)
{
Add-Content c:\temp\computers.log -Value "The following PC $Computer has been found and disabled"
Set-ADComputer $ADComputer -Description "$($ADComputer.Description)- Disable due to inactivity - $(Get-Date) - by $env:UserName " -Enabled $False
}
Else
{
Add-Content c:\temp\computers.log -Value "$Computer not Found in Active Directory or Was disabled before"
}
}
(3)我的csv格式是这样的