PowerShell功能,而不是重复代码

时间:2014-05-23 06:42:40

标签: powershell

最近几天我一直在打破功能和参数。我真的希望能够通过使用Invoke-Command在远程服务器上运行但不重复代码来增强我删除文件的功能。

我希望在我的脚本中能够做到这样的功能:

  • Delete-OldFiles "\\Domain\Share\Dir1" "10" "Auto_Clean.log"
  • Delete-OldFiles "SERVER1" "C:\Share\Dir1" "10" "Auto_Clean.log"

该函数的第一次调用完美无缺,并在本地服务器上执行该函数。在第二次调用时,我想将服务器名称传递给函数,以便它将在远程服务器上执行脚本。

我确定在提供服务器名称时必须有一个选项可以在函数中启用此Invoke-Command而无需编写代码两次...但我只是不能好像是抓住了我的头。

Invoke-Command -ComputerName $_.Server -ScriptBlock ${Function:Delete-OldFiles} -ArgumentList ($_.Server,$_.Path,$_.OlderThanDays,"Auto_Clean.log")

我的功能

Function Delete-OldFiles {
[CmdletBinding(SupportsShouldProcess=$True)] # Add -WhatIf support for dry run
Param(
    [Parameter(Mandatory=$False,Position=1)]
    [String]$Server,
    [Parameter(Mandatory=$True,Position=2)]
    [ValidateScript({Test-Path $_})]
    [String]$Target,
    [Parameter(Mandatory=$True,Position=3)]
    [Int]$OlderThanDays,
    [Parameter(Mandatory=$True,Position=4)]
    [String]$LogName
      )

if ($PSVersionTable.PSVersion.Major -ge "3") {

# PowerShell 3+ Remove files older than (FASTER)
    Get-ChildItem -Path $Target -Exclude $LogName -Recurse -File | 
    Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | ForEach {
        $Item = $_.FullName
        Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue
        $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
        # If files can't be removed
        if (Test-Path $Item)
            { "$Timestamp | FAILLED: $Server $Item (IN USE)" } 
        else
            { "$Timestamp | REMOVED: $Server $Item" }  
        } | Tee-Object $Target\$LogName -Append } # Output file names to console & logfile at the same time

Else {               

# PowerShell 2 Remove files older than
    Get-ChildItem -Path $Target -Exclude $LogName -Recurse | 
    Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | ForEach {
        $Item = $_.FullName
        Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue
        $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
        # If files can't be removed
        if (Test-Path $Item)
            { 
            Write-Host "$Timestamp | FAILLED: $Server $Item (IN USE)"
            "$Timestamp | FAILLED: $Server $Item (IN USE)"
             } 
        else
            { 
            Write-Host "$Timestamp | REMOVED: $Server $Item"
            "$Timestamp | REMOVED: $Server $Item"
            }  
        } |  Out-File $Target\$LogName -Append } 
}

感谢您的帮助。

0 个答案:

没有答案