Home > Back-end >  Powershell - Script working outside function but not in function
Powershell - Script working outside function but not in function

Time:12-29

I'm trying to write a simple function that gets files from designated directory filters them with one criteria a then puts the results back. I came up with this as below. It works if it is not placed in a function and when placed in one it only runs Get-ChildItem and I have no idea why. This is my simple code:

function Move-AllSigned 
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $Path
    )
               
    Process {
        $TempPath = Join-Path -Path $Path -ChildPath '\1'

        Write-Host $TempPath

        Set-Location -Path $Path
        Get-ChildItem -Name "*sig*" | Move-Item -Destination $TempPath
        Remove-Item *.pdf 
        Set-Location -Path $TempPath
        Move-Item * -Destination $Path
    }
}

CodePudding user response:

While I have no explanation for your symptom, you can bypass it by streamlining your code and avoiding Set-Location calls (which are best avoided, because they change the current location session-wide):

Remove-Item (Join-Path $Path *.pdf) -Exclude *sig* -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

The above removes all .pdf files in folder $Path that do not have substring sig in their name - which is what I understand your intent to be.


Wrapped in a function (error handling omitted):

function Remove-AllUnsigned {

  [CmdletBinding(SupportsShouldProcess)]
  param (
      [Parameter(Mandatory)]
      [string] $Path,
      [switch] $Force
  )

  # Ask for confirmation, unless -Force was passed.
  # Caveat: The default prompt response is YES, unfortunately.
  if (-not $Force -and -not $PSCmdlet.ShouldContinue($Path, "Remove all unsigned PDF files from the following path?")) { return }
  
  # Thanks to SupportsShouldProcess, passing -WhatIf to the function
  # is in effect propagated to cmdlets called inside the function.
  Remove-Item (Join-Path $Path *.pdf) -Exclude *sig*

}

Note:

  • Since the function isn't designed to accept pipeline input, there is no need for a process block (though it wouldn't hurt).

  • Since instant deletion can be dangerous, $PSCmdlet.ShouldContinue() is used to prompt the user for confirmation by default - unless you explicitly pass -Force

  • To make the function itself also support the -WhatIf common parameter for previewing the operation, property SupportsShouldProcess in the [CmdletBinding()] attribute is set (implicitly to $true)

  • Related