【问题标题】:Empty (null) PowerShell Variable空(null)PowerShell 变量
【发布时间】:2018-06-27 22:49:51
【问题描述】:

我正在为我的雇主编写一个脚本,它将我们在 Active Directory 中拥有的内容与我们使用的另一个软件中的 CSV 文件进行比较。 Active Directory 应与 CSV 文件匹配。我遇到的问题是 $emplyee 变量总是空的(null):

$employee = Get-ADuser -Filter {EmployeeID -like "$ID"} -properties *

$employee 变量是应该与 foreach 循环中的当前 $user 进行比较的 Active Directory 帐户。在使用 VS Code 中的调试器进行故障排除时,我发现 $employee 变量为空,因此脚本无法比较这两个对象。以下是我正在使用的代码:


$users = Import-Csv C:\Users\Administrator\Desktop\June18Report_2.csv

foreach ($user in $users) {

    $ID = $user.'Employee ID'

    $employee = Get-ADUser -Filter {EmployeeID -eq $ID} -Properties *

    $lastname = $user.'Last Name'

    $samaccountname = $employee.SamAccountName

if ($lastname -ne $employee.surname) {

    Write-Host "The last name was changed for $samaccountname" -ForegroundColor Red

    get-aduser -Identity $employee.SamAccountName | Set-ADUser -Surname $lastname

 } Else {

    Write-Host "The last name is correct for $samaccountname" -ForegroundColor Green 

      }

对于这个问题的任何帮助或提示将不胜感激!

谢谢! - leah_cyberpadawan

【问题讨论】:

  • 试试{EmployeeID -like $ID}(无引号)(编辑:刚刚注意到你在脚本块中有它,但在第一行代码中你有引号)

标签: powershell variables null active-directory


【解决方案1】:

看起来问题可能出在 $employee 变量末尾的通配符上。

$employee = Get-ADUser -Filter {EmployeeID -eq $ID} -Properties (*)

我有一种感觉,这就是为什么您的变量为空的原因。 (即,您可能必须定义要查找的属性,因为通配符可能会尝试提取所有属性。)

**编辑:或者,您可以尝试在 EmployeeID 数据搜索周围放置 (''),从

$employee = Get-ADUser -Filter {EmployeeID -eq $ID} -Properties *

$employee = Get-ADUser -Filter {'EmployeeID' -eq $ID} -Properties *

希望这有助于引导您朝着正确的方向前进!

【讨论】:

  • 我的 PowerShell 系统上没有 AD,但我针对 Get-Command 运行了一个修改版本,最后带有通配符的属性,它运行良好。您可能不得不将结果传递到另一个命令中,并将其设置为您的变量,即使我不确定为什么需要这样做,因为它应该将该输出分配给您的变量。
  • 谢谢你,@iExist!这似乎是问题所在。我的代码现在是$employee = Get-ADUser -Filter {EmployeeID -eq $ID} -Properties surname | Select-Object surname
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 2020-03-25
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
相关资源
最近更新 更多