【发布时间】: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。如果我设置一个断点,执行就会一团糟:
- 在
if (!(Test-Path $backupDir))设置的断点处停止- 我走进去,它转到
if ($backupDir.EndsWith("\*"))- 我走进去,它转到
Write-Host "$backupDir ends with \*!"- 我踏入,它停止运行。
为什么脚本会提前终止?
编辑:我尝试将函数移动到常规的.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