PowerShell module terminating unexpectedly

陌路散爱 提交于 2019-12-25 07:47:48

问题


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.



来源:https://stackoverflow.com/questions/39148473/powershell-module-terminating-unexpectedly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!