PowerShell module terminating unexpectedly

2019-09-04 04:38发布

问题:

A PowerShell module I'm working on is behaving very strangely...

I have the following code in a RestoreTestFiles.psm1 file (located in %USERPROFILE%\My Documents\WindowsPowerShell\Modules\RestoreTestFiles\):

Function Restore-TestFiles([string]$backupDir, [string]$destinationDir, [bool]$overwrite)
{
    if (!(Test-Path $backupDir))
    { 
        Write-Host "Error, $backupDir does not exist."
        return
    }

    if ($backupDir.EndsWith("\*"))
    {
        Write-Host "$backupDir ends with \*!"
    }
    else
    {
        Write-Host "$backupDir does not end with \*."
    }

    if ($overwrite)
    {
        Copy-Item -Path $backupDir -Destination $destinationDir -Recurse -Force
    }
    else
    {
        Copy-Item -Path $backupDir -Destination $destinationDir -Recurse
    }

    Write-Host "Files sucessfully copied from $backupDir to $destinationDir."
}

And I call the function like this:

Import-Module RestoreTestFiles

Restore-TestFiles "C:\some\path\*" "C:\someOther\path\"

For some reason, the output is only either

C:\some\path\* ends with \*!

or

C:\some\path does not end with \*.

But it never runs the Copy-Item or the final Write-Host. If I set a breakpoint, the execution is all messed up:

  1. Stops at breakpoint set on if (!(Test-Path $backupDir))
  2. I step into and it goes to if ($backupDir.EndsWith("\*"))
  3. I step into and it goes to Write-Host "$backupDir ends with \*!"
  4. I step into and it stops running.

Why is the script terminating before it is supposed to?

Edit: I tried moving the function to a regular .ps1 script and called the function from the same script and it works fine...it only terminates prematurely if the function is in a module and called from outside the module. What gives?

回答1:

I was able to fix this by completely closing all open instances of the PowerShell ISE and re-opening my module.