我需要帮助找出我的代码挂在哪里

问题描述 投票:0回答:1

我的任务是编写一个 PowerShell 脚本,我可以在我的组织的计算机上运行该脚本来清理 Windows 中的旧用户配置文件。 该脚本的目标是获取电脑上的用户列表,根据名称排除某些帐户,然后在超过 90 天未使用的情况下将其删除。 我确信有一种更简单的方法来删除配置文件,但这也会删除配置文件的注册表项。

$User = get-childitem -Path C:\Users -Name
#Current Date for comparison
$Cutoff = (Get-Date).AddDays(-90)
#Cut Public and Administrator accounts from the list
$Userlist = @()
foreach ($User in $Users) {
    if ($User -in "Public", "Administrator", "administrator", ".Net v4.5", ".Net v4.5 classic", ".Default", "itadmin", "it-admin", "cpsi") {
        # Skip the user if their name is in the exclusion list
        continue
    }

    try {
        $Userlist.Add($User)
    }
    catch {
        Write-Host "Could not add the user $User to the Userlist."
    }
}
#Gather all Login events in the $events variable
$Events = Get-WinEvent -FilterHashtable @{ LogName='Security'; Id='4624'; StartTime=(Get-Date).AddDays(-90)}
$LogList = @{}
$user -lt ($cutoff) 
#Loop through the previously gathered list is users
foreach ($User in $Userlist){
#Filter the Events for ones performed by the user and store it in $Logins
$Logins = $Events| Where {$_.Message -like "*$User*" -and $_.Message -like "*@tchospital.local*"}
#Output line ($Logins | Measure).Count will output the number of times the user login during the currently available security logs
$LoginCount = ($Logins | Measure).Count
if($LoginCount -eq 0){
$RemovedUserList =@($RemovedUserList + $User)
$UserFolder = "C:\Users\$User"
Get-WmiObject -Class Win32_UserProfile | Where LocalPath -eq $UserFolder | Remove-WmiObject}
else{
continue
}
}
$CutOut = Write-Output "Cutoff date is $Cutoff"
$UserOut = Write-Output "Found users are: $Userlist"
$Today = Get-Date
$RunDate= Write-Output "Rundate is: $Today"
if (!($RemovedUserList)){
$RemovedUser = Write-Output "No one has been removed"
}
else{
$RemovedUser = Write-Output "$RemovedUserList has been removed"
}

我对 PowerShell 不太熟悉,所以我认为我的所有格式都正确。但在编写脚本方面我绝对是一个初学者。

这应该执行以下操作: 在变量 $User 下创建用户列表 从列表中排除某些配置文件 使用事件日志查看他们的登录时间 使用 get-wmiobject 删除配置文件

如果有人能帮助我那就太好了。

windows powershell scripting system-administration windows-scripting
1个回答
0
投票
  1. 正如达林在评论中所说,你已经分配了结果 Get-ChildItem 到 $User,当您指的是 $Users 时。

  2. 我倾向于使用 Powershell 5.1 来实现兼容性,但 $Userlist 在第 5 行被声明为一个数组(具有固定大小)。为了使

    $Userlist.Add($User)
    语法正常工作,它需要是一个 arrayList。您有两个选择:

最简单:使用 += 运算符。数组在 powershell 中是不可变的,但对于小 n 来说,这还不错:

$Userlist = @()
$Userlist += $User

不太简单,但更快:

$Userlist = [System.Collections.ArrayList]::new()
[void] $Userlist.Add($User) # the void cast just hides the output, the index to which the element was added
  1. 你用这条线做什么?
    $user -lt ($cutoff)
    。它只是将 true 或 false 打印到控制台,对流量控制没有影响。

可能还有更多,但我必须走了。我的脚本即将运行完毕。希望这能让您起步。

© www.soinside.com 2019 - 2024. All rights reserved.