PowerShell默认值不起作用

时间:2014-06-11 08:27:51

标签: powershell

我试图用一些变量来提供我的函数,当没有给出变量时,它应该使用OlderThanDays的默认值30。出于这样或那样的原因,这并不像我预期的那样有效。

我使用if($_.B -ne $null) {$OlderThanDays=$_.B} else {$OlderThanDays="30"}在ForEach循环中解决了我的问题但我不认为这是最佳做法。谁能告诉我为什么[Int]$OlderThanDays=30不起作用?

问题:在我的csv文件中添加一行而没有定义OlderThanDays变量时,默认情况下不使用30天,文件只是被删除...

感谢您的帮助。

CSV文件:

# Correct input formats are:
#
# ServerName, LocalPath, OlderThanDays
# Ex: server, E:\SHARE\Target, 10 
# Ex: server, E:\CBR\SHARE\Target
#
# UNC-Path, OlderThanDays
# Ex: \\domain\SHARE\Target, 20
# Ex: \\domain\Target
#
# If no 'OlderThanDays' is provided, a default of 30 days will be used
# Commenting out can be done with '#'
# ______________________________________________________________________

SERVER1, E:\SHARE\Target
\\domain\SHARE\Target2

完整脚本:

#__________________________________________________________________________________________________________________________________
$ImportFile = "S:\Input\Scheduled Task\Auto_Clean.csv"
$Password = cat "S:\Input\pwd.txt" | ConvertTo-SecureString -Force
$UserName = "domain\me"
#__________________________________________________________________________________________________________________________________
# Scriptblock for running the function in a job
$JobCall = {
    # Function that removes files older than x days in all subfolders
    Function Delete-OldFiles {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param(
        [Parameter(Mandatory=$True,Position=1)]
        [ValidateScript({Test-Path $_})]
        [String]$Target,
        [Parameter(Mandatory=$False,Position=2)]
        [Int]$OlderThanDays=30,
        [Parameter(Mandatory=$False,Position=3)]
        [String]$Server,
        [switch]$CleanFolders
          )

    #__________________________________________________________________________________________________________________________________
    # Create logfile 
    $TempDate = (get-date).ToString("dd-MM-yyyy")
    $TempFolderPath = $Target -replace '\\','_'
    $TempFolderPath = $TempFolderPath -replace ':',''
    $TempFolderPath = $TempFolderPath -replace ' ',''

    $script:LogFile = "\\DEUSTHEIDIT02\Log\Scheduled Task\Auto_Clean\$Server - $TempFolderPath - $TempDate.log"

    #__________________________________________________________________________________________________________________________________
    # Check the version of PowerShell
    if ($PSVersionTable.PSVersion.Major -ge "3") {

        # PowerShell 3+ Remove files older than (FASTER)
        Get-ChildItem -Path $Target -Recurse -File | 
        Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | 

            ForEach {
            $Item = $_.FullName
            Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue

                # Log succes/failure
                $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
                if (Test-Path $Item) { 
                    "$Timestamp | FAILLED: $Server $Item (IN USE)"
                } 
                else { 
                    "$Timestamp | REMOVED: $Server $Item" 
                }  
            } | Tee-Object $LogFile -Append -Verbose}

    Else {               

        # PowerShell 2 Remove files older than
        Get-ChildItem -Path $Target -Recurse | 
        Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | 

            ForEach {
            $Item = $_.FullName
            Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue

                # Log succes/failure
                $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()   
                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 $LogFile -Append } 

    #__________________________________________________________________________________________________________________________________
        # Switch -CleanFolders deletes empty folders older than x days
        if ($CleanFolders) {

            # Check the version of PowerShell
            if ($PSVersionTable.PSVersion.Major -ge "3") {

                # PowerShell 3+ Remove empty folders older than (FASTER)
                Get-ChildItem -Path $Target -Recurse -Force -Directory  -ErrorAction SilentlyContinue |
                Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | 
                Where-Object { (Get-ChildItem -Path $_.FullName -Recurse -Force -File) -eq $null } | 

                    ForEach {
                    $Item = $_.FullName
                    Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue

                        # Log succes/failure
                        $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()
                        if (Test-Path $Item) { 
                            "$Timestamp | FAILLED: $Server $Item (IN USE)" 
                        } 
                        else { 
                            "$Timestamp | REMOVED: $Server $Item" 
                        }  
                    } | Tee-Object $LogFile -Append
            }     

            else {

                # PowerShell 2 Remove empty folders older than 
                Get-ChildItem -Path $Target -Recurse -Force -ErrorAction SilentlyContinue | 
                Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | 
                Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$OlderThanDays) } | 

                    ForEach {
                    $Item = $_.FullName
                    Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue

                        # Log succes/failure
                        $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
                        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 $LogFile -Append 
            } 
        }
    }
# Lact command of the ScriptBlock: Call the magic to happen
Delete-OldFiles $args[0] $args[1] $args[2] -CleanFolders:$args[3]
}

#__________________________________________________________________________________________________________________________________
# Read input file and ignore all lines starting with #
$File = (Import-Csv -Path $ImportFile -Header "A", "B", "C", "D" | Where { $_.A -NotLike "#*" } )

#__________________________________________________________________________________________________________________________________
# If the UNC Path is provided we will run the script locally else it wil be run on the remote server as a job
Foreach ($_ in $File) {

    # Define input format & default values
    if ($_.A -like "\\*") {
        $Server="UNC"
        $Target=$_.A
        $OlderThanDays=$_.B
        $CleanFolders=$_.C
    }
    else {
        $Server=$_.A
        $Target=$_.B
        $OlderThanDays=$_.C
        $CleanFolders=$_.D        
    }

            # Call the scriptblock with the function to run locally or on the remote server
            if ($Server -eq "UNC")
            {
                Write-Host "UNC Path detected: $Target, $OlderThanDays" -ForegroundColor Yellow
                Start-Job -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server) -Name DelFiles
            }
            else
            {
                Write-Host "Local path detected: $Server, $Target, $OlderThanDays" -ForegroundColor Cyan
                $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$Password            
                Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server) -ComputerName "$Server.domain" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles

                # Delete empty folders: Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $true) -ComputerName "$Server.domain" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles
            }  
}

2 个答案:

答案 0 :(得分:1)

该参数既不是必需的,也有默认值。首先检查前者,如果它被设置为$true,则默认值被忽略。如果您想确保用户无法指定空值,只需使用[ValidateNotNullorEmpty()]验证,并使参数可选。

答案 1 :(得分:0)

所以我有一个类似的问题。几个月后,使用日常功能的个人功能模块广泛使用默认值,并且在许多情况下使用带有初始化默认值的强制性参数,突然我的功能停止工作。 编写新变量后,使用显式参数调用它将导致函数执行上下文中的参数值为空。 重新启动Powershell控制台一段时间后,我决定重新启动计算机,一切恢复正常。走吧。

相关问题