You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用指定Param参数通过PowerShell获取AD中的计算机?

Hey there, let's get your PowerShell script for fetching AD computers working with those parameters you defined. The issue is likely that your parameter block is set up, but you're missing the actual Active Directory query logic and some key checks. Let's walk through a complete, working solution and break down what might have been going wrong.

First, Let's Cover Prerequisites

Before diving into the script, make sure you have the ActiveDirectory PowerShell module installed:

  • On Windows Server: It's included by default with AD DS roles, but you can install it via Install-WindowsFeature RSAT-AD-PowerShell if needed.
  • On Windows 10/11: You'll need to install the RSAT (Remote Server Administration Tools) for AD PowerShell via Settings → Apps → Optional Features → Add a feature, then search for "RSAT: Active Directory Domain Services and Lightweight Directory Tools".

Complete Working Script

Here's how to integrate your parameters with a functional AD query, including debugging and error handling:

#Requires -Modules ActiveDirectory

Param(
    [string] $ComputerName = $env:computername,
    [int] $NumberOfDays = 10,
    [switch] $DebugInfo
)

# Calculate the date threshold for filtering recent activity
$cutoffDate = (Get-Date).AddDays(-$NumberOfDays)

# Build our AD filter (adjust matching logic if you need exact vs fuzzy matches)
$adFilter = "Name -like '*$ComputerName*' -and LastLogonDate -ge `$cutoffDate"

# Output debug info if the switch is enabled
if ($DebugInfo) {
    Write-Host "Debug: Using AD filter: $adFilter" -ForegroundColor Yellow
    Write-Host "Debug: Cutoff date for last logon: $cutoffDate" -ForegroundColor Yellow
}

try {
    # Retrieve AD computer objects with relevant properties
    $matchingComputers = Get-ADComputer -Filter $adFilter -Properties LastLogonDate, OperatingSystem, Enabled
    
    if ($matchingComputers) {
        # Display results in a readable format
        $matchingComputers | Select-Object Name, OperatingSystem, Enabled, LastLogonDate | Format-Table -AutoSize
    } else {
        Write-Host "No computers found matching your criteria:`n- Computer name contains '$ComputerName'`n- Last logged on within the last $NumberOfDays days" -ForegroundColor Cyan
    }
}
catch {
    Write-Error "Failed to retrieve AD computer data: $_"
    if ($DebugInfo) {
        Write-Host "Debug: Full error details: $($_.Exception.Message)" -ForegroundColor Red
    }
}

Key Explanations & Fixes

  1. Parameter Integration:

    • $ComputerName defaults to your local machine name, and we use -like '*$ComputerName*' for fuzzy matching (change to -eq '$ComputerName' if you need exact matches).
    • $NumberOfDays sets a cutoff date for filtering computers that have logged on recently.
    • $DebugInfo switch lets you see the filter and cutoff date to troubleshoot mismatches.
  2. Common Pitfalls to Avoid:

    • Permissions: Ensure the account running the script has read access to Active Directory computer objects.
    • LastLogon vs LastLogonDate: We use LastLogonDate because it's a replicated attribute (works across all domain controllers), whereas LastLogon is specific to individual DCs and requires more work to aggregate.
    • Missing Module: The #Requires line ensures the script won't run unless the ActiveDirectory module is available, preventing confusing runtime errors.

Usage Examples

  • Run with default settings (find your local computer's AD entry if it logged on in the last 10 days):
    .\Get-ADComputers.ps1
    
  • Find all computers starting with "WIN-" that logged on in the last 30 days:
    .\Get-ADComputers.ps1 -ComputerName "WIN-" -NumberOfDays 30
    
  • Enable debugging to see exactly what filter is being used:
    .\Get-ADComputers.ps1 -DebugInfo
    

内容的提问来源于stack exchange,提问作者Dhonovan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:25:17