【问题标题】:PowerShell Script Loop - Alert New Files CreatedPowerShell 脚本循环 - 警告已创建新文件
【发布时间】:2016-08-17 09:38:57
【问题描述】:

我希望有 PowerShell 经验的人能善意地建议(如果可能的话)我们如何循环这个脚本。不幸的是,我们还不太熟悉 PowerShell 脚本循环,并且正在寻找一些建议,哪些是最好的方法/方式。我们在工作中使用下面的脚本向员工发送电子邮件警报,当在指定日期开始的指定文件夹和/或多个文件夹中创建新文件时,它包含一个列出该文件的 .csv 文件,然后将其删除。我们不需要保留发送警报后生成的 .csv 文件。现在我们正在一遍又一遍地复制和粘贴代码,并在添加新文件夹时修改其中的一部分。但是,我们担心的是,随着文件夹随着周/月/年的流逝而添加,并且必须添加新文件夹,最终该文件将成为页面。

理想情况下,我们将对脚本进行的唯一更改是在网络驱动器中查找的文件夹路径、创建时间以及它将要发送到的收件人。

非常感谢任何有关实现所有或任何目标的最佳方式的建议。

非常感谢!!!

$arr = @()
$file = "\\DesignatedNetworkDrive\NewFileFinderReport.csv"
$mesg = "Please see the attached file for a list of files that were created after July 1, 2016."


# Folder: Corporateshare

gci \\DesignatedNetworkDrive\,\\DesignatedNetworkDrive\Corporateshare\  | Where-Object { $_.CreationTime -ge "07/02/2016" } | % {
  $obj = New-Object PSObject
  $obj | Add-Member NoteProperty FullName $_.FullName
  $obj | Add-Member NoteProperty Length $_.Length
  $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)
  $obj | Add-Member NoteProperty LastAccessTime $_.LastAccessTime
  $obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
  $obj | Add-Member NoteProperty CreationTime $_.CreationTime

  $arr += $obj
  }
  $arr | Export-CSV -notypeinformation "$file"



if ($(get-item -path "$file").length -gt 0) {send-mailmessage -from "sysadmin@something.com" -to "jendoe@something.com","johndoe@something.com" -subject "New File Found in Corporateshare" -body "$mesg" -Attachments "$file" -smtpServer mail.somecompany.com}

Remove-Item $file



# Folder: Administration
$arr = @()
$file = "\\DesignatedNetworkDrive\NewFileFinderReport.csv"
$mesg = "Please see the attached file for a list of files that were created after May 3, 2016."


gci \\DesignatedNetworkDrive\Administration\,\\DesignatedNetworkDrive\Administration\_Private\  | Where-Object { $_.CreationTime -ge "05/04/2016" } | % {
  $obj = New-Object PSObject
  $obj | Add-Member NoteProperty FullName $_.FullName
  $obj | Add-Member NoteProperty Length $_.Length
  $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)
  $obj | Add-Member NoteProperty LastAccessTime $_.LastAccessTime
  $obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
  $obj | Add-Member NoteProperty CreationTime $_.CreationTime

  $arr += $obj
  }
  $arr | Export-CSV -notypeinformation "$file"



if ($(get-item -path "$file").length -gt 0) {send-mailmessage -from "jendoe@something.com","johndoe@something.com" -body "$mesg" -Attachments "$file" -smtpServer mail.somecompany.com}

Remove-Item $file


# Folder: Procurement
$arr = @()
$file = "\\DesignatedNetworkDrive\NewFileFinderReport.csv"
$mesg = "Please see the attached file for a list of files that were created after May 24, 2016."


gci \\DesignatedNetworkDrive\Procurement\  | Where-Object { $_.CreationTime -ge "05/25/2016" } | % {
  $obj = New-Object PSObject
  $obj | Add-Member NoteProperty FullName $_.FullName
  $obj | Add-Member NoteProperty Length $_.Length
  $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)
  $obj | Add-Member NoteProperty LastAccessTime $_.LastAccessTime
  $obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
  $obj | Add-Member NoteProperty CreationTime $_.CreationTime

  $arr += $obj
  }
  $arr | Export-CSV -notypeinformation "$file"



if ($(get-item -path "$file").length -gt 0) {send-mailmessage -from "jendoe@something.com","johndoe@something.com" -subject "New File Found in Procurement" -body "$mesg" -Attachments "$file" -smtpServer mail.somecompany.com}

Remove-Item $file

【问题讨论】:

  • 看起来最简单的方法是让它使用 Import-CSV 从配置文件中提取信息,然后使用 ForEach 循环遍历它。如果你想让它编码得很好,你可能也应该把它分成函数——例如,参见 Mathias 的答案。

标签: csv powershell


【解决方案1】:

您需要将过程抽象为一个函数

将 PowerShell 代码的 sn-p 转换为有用函数的关键是识别其中的 变量 部分 - 这些应该转换为您可以使用的 参数然后在调用时传递给函数。

看你的代码,变量很少,即:

  • 创建日期
  • 文件夹路径

此外,您可能希望允许选择性地更改电子邮件收件人、邮件主题和 SMTP 服务器 - 这些可能会在未来发生变化,或因特定目的而有所不同。

考虑到这一点,我们最终会得到这样的结果:

function Check-NewFiles 
{
    param(
        [Parameter(Mandatory)]
        [string[]]$Path,
        [Parameter(Mandatory)]
        [datetime]$CreatedAfter,
        [string]$Subject = "New files found",
        [string[]]$Recipients = @("jendoe@something.com","johndoe@something.com"),
        [string]$MailFrom = "noreply@something.com",
        [string]$SmtpServer
    )

    # Folder: Administration
    $arr = @()
    $file = "\\DesignatedNetworkDrive\NewFileFinderReport.csv"
    $mesg = "Please see the attached file for a list of files that were created after {0:MMM dd, yyyy}" -f $CreatedAfter

    Get-ChildItem $Path  | Where-Object { $_.CreationTime -ge $CreatedAfter } | ForEach-Object {
        $obj = New-Object PSObject
        $obj | Add-Member NoteProperty FullName $_.FullName
        $obj | Add-Member NoteProperty Length $_.Length
        $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)
        $obj | Add-Member NoteProperty LastAccessTime $_.LastAccessTime
        $obj | Add-Member NoteProperty LastWriteTime $_.LastWriteTime
        $obj | Add-Member NoteProperty CreationTime $_.CreationTime

        $arr += $obj
    }
    $arr | Export-CSV -notypeinformation "$file"



    if ($(get-item -path "$file").length -gt 0) {
        Send-MailMessage -From $MailFrom -body "$mesg" -Attachments "$file" -smtpServer $SmtpServer -To $Recipients
    }

    Remove-Item $file
}

现在你每次都可以用一行代码调用它:

Check-NewFiles -Path \\DesignatedNetworkDrive\,\\DesignatedNetworkDrive\Corporateshare\ -CreatedAfter '07/02/2016'
Check-NewFiles -Path \\DesignatedNetworkDrive\Administration\,\\DesignatedNetworkDrive\Administration\_Private\ -CreatedAfter '05/04/2016'

对于具有大量参数的同一调用的许多实例,我喜欢设置带有参数参数的哈希表集合 - 这样我可以轻松地循环整个集合并在 splatting 时调用函数参数:

$FoldersToWatch = @(
    # Folder: Corporateshare
    @{
        Path = '\\DesignatedNetworkDrive\','\\DesignatedNetworkDrive\Corporateshare\'
        CreatedAfter = "07/02/2016"
        MailFrom = "sysadmin@something.com" 
        Recipients = "jendoe@something.com","johndoe@something.com"
    },

    # Folder: Administration
    @{
        Path = '\\DesignatedNetworkDrive\Administration\','\\DesignatedNetworkDrive\Administration\_Private\'
        CreatedAfter = "05/04/2016"
        Recipients = "jendoe@something.com","johndoe@something.com"
    },

    # Folder: Procurement
    @{
        Path = '\\DesignatedNetworkDrive\Procurement\'
        CreatedAfter = "05/25/2016"
        Subject = "Procurement, IMPORTANT!"
    }
)

现在,将上面的内容放在它自己的文件中,命名为FoldersToWatch.ps1

然后,在定义Check-NewFiles 函数的脚本中,点源FoldersToWatch.ps1 文件,然后循环遍历哈希表并调用函数:

# function Check-NewFiles goes up here

. .\FoldersToWatch.ps1

$FoldersToWatch |Foreach-Object {
    Check-NewFiles @_
}

你有它。现在任何人都可以更新FoldersToWatch.ps1 中的参数,而不会弄乱脚本本身,也不会忽视正在发生的事情。


我还想指出,使用New-ObjectAdd-Member 创建新对象然后将其添加到数组中的方式完全没有必要。使用Select-Object 并将其直接通过管道传递给Export-Csv

Get-ChildItem $Path |Where-Object { $_.CreationTime -ge $CreatedAfter } |Select-Object FullName,Length,@{Label='Owner';Expression={(Get-Acl $_.FullName).Owner}},LastAccessTime,LastWriteTime,CreationTime |Export-CSV -notypeinformation "$file"

最终的函数看起来更像:

function Check-NewFiles 
{
    param(
        [Parameter(Mandatory)]
        [string[]]$Path,
        [Parameter(Mandatory)]
        [datetime]$CreatedAfter,
        [string]$Subject = "New files found",
        [string[]]$Recipients = @("jendoe@something.com","johndoe@something.com"),
        [string]$MailFrom = "noreply@something.com",
        [string]$SmtpServer
    )

    $file = "\\DesignatedNetworkDrive\NewFileFinderReport.csv"
    $mesg = "Please see the attached file for a list of files that were created after {0:MMM dd, yyyy}" -f $CreatedAfter

    Get-ChildItem $Path |Where-Object { $_.CreationTime -ge $CreatedAfter } |Select-Object FullName,Length,@{Label='Owner';Expression={(Get-Acl $_.FullName).Owner}},LastAccessTime,LastWriteTime,CreationTime |Export-CSV -notypeinformation "$file"

    if ($(get-item -path "$file").length -gt 0) {
        Send-MailMessage -From $MailFrom -body "$mesg" -Attachments "$file" -smtpServer $SmtpServer -To $Recipients
    }

    Remove-Item $file
}

【讨论】:

  • 除此之外,让它从文件中提取参数可能是个好主意 - 最简单的解决方案是使用 Import-CSV,然后使用 ForEach 循环或调用 Invoke-Command。
  • @Larkeith 我通常定义第二个脚本,其中包含用于函数调用的 splatting 表,添加示例来回答
  • 非常感谢@MathiasR.Jessen。非常感谢您的彻底回应。非常适合我的学习体验。
  • @MathiasR.Jessen 这绝对是另一个不错的选择;我喜欢 CSV 的主要原因是它可以用 Excel 进行编辑,但任何一种方式都是 100% 可行的,特别是因为 splatting tables 支持 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2012-07-02
  • 1970-01-01
  • 2017-04-17
  • 2013-08-06
相关资源
最近更新 更多