添加 nslookup 命令后 PowerShell 中没有返回值

No Returning value in PowerShell after adding nslookup command

添加代码后

$ip = (nslookup $pcName | Select-String Address | Where-Object LineNumber -eq 5).ToString().Split(' ')[-1]

当用户没有为他的用户 ID 分配电脑名称时,它不会给出任何结果。该脚本没有 运行,它给出了一个空白结果。当用户为其用户 ID 分配了 PC 名称时,它会起作用。

由于输入错误或其他原因无法找到用户 ID 时也是如此。我想提示用户输入正确的用户 ID 并重新启动脚本。我正在尝试弄清楚它是如何完成的,但我没有找到正确的方法。

在此先感谢您的帮助!

$csv = Import-CSV 'C:\Users\ADMIN\Desktop\Powershells\Computers in a specific workgroup or domain.csv'
$ADprops = @(
    'DisplayName'
    'Mail'
    'LastBadPasswordAttempt'
    'AccountExpirationDate'
    'PasswordLastSet'
)

$filter = @(
    $ADprops
    @{ 
        Name = 'Password Changeable'
        Expression = { $changeable }
    }, @{
        Name = 'Password Expires'
        Expression = { $expires }
    }, @{
        Name = 'Last logon'
        Expression = { $lastlogon }
    }, @{
        Name = 'PC Name'
        Expression = { $pcName }
    }, @{   
        Name = 'Address'
        Expression = { $ip }
    }

)

Clear-Host
do
{
    Write-Host " Enter the user ID: " -ForegroundColor Cyan -NoNewline
    $UserName = Read-Host
    Write-Host ""

    $pcName = $csv.Where({ $_."User ID" -match $Username })."PC Name"
    $ip = (nslookup $pcName | Select-String Address | Where-Object LineNumber -eq 5).ToString().Split(' ')[-1]
    $expires, $changeable = net user $Username /domain |
    Select-String -Pattern 'Password Changeable|Password Expires|Last logon'|
    ForEach-Object { ($_ -split '\s{2,}')[1] }
    Get-ADUser -Identity $Username -Properties $ADprops |
    Select-Object $filter

} while ($Username -notcontains $Processes)

在测试您的代码时,我注意到当您为函数 nsloockup 提供空字符串值时,该函数会卡住。我的建议是添加对 $pcName 变量的检查,如下所示:

$pcName = $csv.Where({ $_."User ID" -match $Username })."PC Name"
if([string]::IsNullOrEmpty($pcName)){
    continue;
}