删除超过x天的域配置文件

时间:2016-04-28 18:57:42

标签: windows powershell

我需要一些帮助才能完成脚本,我已经有了删除远程服务器上特定配置文件的脚本,但我想要添加时间框架。示例:如果配置文件的使用时间超过120天,请将其删除。

Function Get-OldProfiles {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)] [string]$computerName
)


PROCESS {
    foreach ($computer in $computerName) {
        Write-host -ForegroundColor Yellow  "Housekeeping on $computer"
        Write-host -ForegroundColor Yellow  "Mapping drive \\$computer\c$"
        $drive = New-PSDrive -Name $computer.replace(".","-") -PSProvider FileSystem -Root \\$computer\C$ 
        Write-host -ForegroundColor Yellow  "Checking windows version"
        #Cheking windows version
        $version = (Get-WmiObject -ComputerName $computer -Class Win32_OperatingSystem).version
        Write-host -ForegroundColor Yellow  "Windows version $version"


        #Profile Deleting area.
        if ($version -ge 6) {
            Write-host -ForegroundColor Yellow  "Getting profiles from WMI"
            $profiles = Get-WmiObject -ComputerName $computer Win32_UserProfile -filter "LocalPath Like 'C:\\Users\\%'" | Where-object localpath -Match 'B.{5}R$'| Select-Object {$_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-2)}
            if ($profiles -ne $null)  {
                $profiles | foreach { 
                Write-host -ForegroundColor Red  ("Deleting profile: " + $_.LocalPath)
                #$_.Delete()
                    }
                }
            }
        }
    }
}

我试过这个:

$profiles= Get-WmiObject -ComputerName $computer -class Win32_UserProfile -filter "Special = False -and LocalPath Like 'C:\\Users\\%'" | Where-object localpath -Match 'B.{5}R$' | Where {$_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-120)}

但它返回错误

Get-WmiObject : Invalid query "select * from Win32_UserProfile where Special = False -and LocalPath Like 'C:\\Users\\%'"
At line:22 char:24 + $profiles= Get-WmiObject -ComputerName $computer -class Win32_UserPr ...

1 个答案:

答案 0 :(得分:0)

您不能在WQL过滤器中使用-and,它只是AND。尝试:

$profiles = Get-WmiObject -ComputerName $computer -Class Win32_UserProfile -filter "Special = False AND LocalPath Like 'C:\\Users\\%'" |
Where-Object { ($_.localpath -Match 'B.{5}R$') -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-120)) }