Home > Software engineering >  Script running fine locally but throwing error while running on server
Script running fine locally but throwing error while running on server

Time:09-07

Sorry but I checked all the other post similar to this, but could not find the working solution.

error:- Get-ChildItem : A parameter cannot be found that matches parameter name 'File'.

I want to delete files older than 30 days from folder and sub folder. Script running fine locally but throwing error while running on server. powershell version is 5. Any help is appreciated! script:-

Get-ChildItem –Path "D:\file\source" –Include *.* -File -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item

CodePudding user response:

Here is a delete function that I use. I confirmed that it will run on the 5.1 Powershell you are using:

function DeleteOldFiles {
    param (
        [string]$file
    )
    Remove-Item -Path $file
}

Set-Location 'D:\file\source'
    
    $fileList = Get-ChildItem -Depth 1 | Where-Object {$_.PSIsContainer -eq $false -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)}

    foreach($f in $fileList)
    {
        DeleteOldFiles -file $f.FullName
    }

CodePudding user response:

tl;dr

If your server is running a PowerShell version greater than or equal to 3.0 - which you report to be the case (v5.1) - the implication is that your server has no D: drive or, at least hypothetically, that D: is not a file-system drive, but backed by a different PowerShell provider.


While it is true that the -File switch parameter (along with -Directory) wasn't available until version 3 of PowerShell, the error message you saw - A parameter cannot be found that matches parameter name 'File' - can situationally also occur in later versions, because it is a so-called dynamic parameter that is specific to the PowerShell's FileSystem provider.

That is, the parameter isn't available if you combine -File with:

  • a path based on a drive whose provider is a provider other than the FileSystem provider (with relative paths, the drive is implied by the current location)

  • a path referencing a drive that doesn't exist.

The resulting error message (quoted above) does not distinguish between those two cases.

An easy way to provoke the error is with the following command:
Get-ChildItem variable:* -File

  • Related