Powershell 脚本不会听 if 语句

Powershell script won't listen to if statement

我真的很不擅长编写脚本,我需要你的帮助。我从互联网上的几个地方拼凑了这个脚本并且它有效,直到我启用我的 IF 语句...

我只是想从 UNC 路径获取文件夹的文件数,如果它超过指定数量,那么我希望它发送一封电子邮件让我知道当前计数。

但是,如果我取消注释 if ($count -gt 50) 部分,那么如果计数超过 50,我将不会收到电子邮件。

我不知道如何使“.Count”成为我在脚本其他地方使用的变量。有人可以帮忙吗?

然后我需要弄清楚如何 运行 它。正在考虑 windows 中的计划任务并每隔几分钟或其他时间 运行,但如果您有更好的想法,我想听听他们!

$FolderList = @(
    "\server\path\test"
        )
$Body = ($FolderList | ForEach-Object {
    "Check to see if Sweep Service is running, file count for '$($_)':  " + (Get-ChildItem -Path $_ -File -ErrorAction SilentlyContinue | Measure-Object).Count
}) -join "`r`n"

#if ($count -gt 50)
#{
    $From = "me@you.com"
    $To = "me@you.com"
    $Subject = "Sweep Checker"
    $SmtpServer = "webmail.you.com"
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SmtpServer
#}

您的主要问题似乎是没有将文件计数保存到任何变量。相反,您将该值保存为字符串的一部分 - 而不是数字。 [咧嘴一笑]

下面的代码明确地将当前目录的文件计数放入一个 var 中,将其添加到 total 计数中,然后使用当前计数构建输出字符串你的消息正文。

$FolderList = @(
    $env:TEMP
    $env:USERPROFILE
    $env:ALLUSERSPROFILE
        )
$TriggerFileCount = 20
$TotalFileCount = 0

$Body = foreach ($FL_Item in $FolderList)
    {
    $CurrentFileCount = @(Get-ChildItem -LiteralPath $FL_Item -File -ErrorAction SilentlyContinue).Count
    $TotalFileCount += $CurrentFileCount

    # send out to the "$Body" collection
    'Check to see if Sweep Service is running, file count for [ {0} ] = {1}' -f $FL_Item, $CurrentFileCount
    }

if ($TotalFileCount -gt $TriggerFileCount)
    {
    $SMM_Params = @{
        From = 'NotMe@example.com'
        To = 'NotYou@example.com'
        Subject = 'Sweep Checker'
        Body = $Body -join [System.Environment]::NewLine
        SmtpServer = $SmtpServer
        }

    $SMM_Params

    #Send-MailMessage @SMM_Params
    }

输出...

Name                           Value
----                           -----
Subject                        Sweep Checker
From                           NotMe@example.com
To                             NotYou@example.com
SmtpServer                     webmail.you.com
Body                           Check to see if Sweep Service is running, file count for [ C:\Temp ] = 22...

$Body变量的全部内容...

Check to see if Sweep Service is running, file count for [ C:\Temp ] = 22
Check to see if Sweep Service is running, file count for [ C:\Users\MyUserName ] = 5
Check to see if Sweep Service is running, file count for [ C:\ProgramData ] = 0