【问题标题】:PowerShell module terminating unexpectedlyPowerShell 模块意外终止
【发布时间】:2016-08-25 14:51:04
【问题描述】:

我正在处理的一个 PowerShell 模块的行为非常奇怪...

我在RestoreTestFiles.psm1 文件(位于%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."
}

我这样调用函数:

Import-Module RestoreTestFiles

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

由于某种原因,输出只有一个

C:\some\path\* 以 \*! 结尾

C:\some\path 不以 \* 结尾。

但它永远不会运行Copy-Item 或最终的Write-Host。如果我设置一个断点,执行就会一团糟:

  1. if (!(Test-Path $backupDir)) 设置的断点处停止
  2. 我走进去,它转到if ($backupDir.EndsWith("\*"))
  3. 我走进去,它转到Write-Host "$backupDir ends with \*!"
  4. 我踏入,它停止运行。

为什么脚本会提前终止?

编辑:我尝试将函数移动到常规的.ps1 脚本并从同一个脚本调用该函数,它工作正常......它只会在函数位于模块中时提前终止并从模块外部调用。什么给了?

【问题讨论】:

  • $Overwrite 应该是 [Switch] 而不是 [bool]。不确定它是否会帮助解决这个特定问题
  • 要开始调试,请运行以下命令行$Error.Clear(); <your commands>; $Error
  • @Eris 为什么应该是switch?我可以看到,如果没有提供switch 参数,它将默认为$False,但为什么bool 错误?
  • @Eris 运行$Error.Clear() 修复了脚本执行,但我想我现在的问题是......为什么?感谢大家的帮助!
  • switch vs bool: a [Switch] 让我们说-Overwrite 没有值,它的计算结果为$true,布尔值将计算为$false

标签: powershell powershell-module


【解决方案1】:

我能够通过完全关闭 PowerShell ISE 的所有打开实例并重新打开我的模块来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多