运行powershell -command时找不到类型

9
我有一个PowerShell脚本,我想在Bamboo中将其用作部署步骤。在PowerShell中打开并使用./script.ps1运行脚本是可以的,但是使用powershell.exe -command ./script.ps1会出现错误Unable to find type [Microsoft.PowerShell.Commands.WebRequestMethod]
直接从PowerShell运行脚本和使用powershell.exe -command有什么区别?我漏了什么?
问题的MWE:
function Test-RestMethod {
    param([string]$Uri, [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get')

    $result = Invoke-RestMethod $uri -Method $Method
    return $result
}

Test-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ -Method 'Get' | Format-Table -Property Title, pubDate

我猜测你的PowerShell路径返回的可能是不同的版本,请尝试使用Get-Host来确定每种方法所使用的版本。 - David Martin
它们都使用相同的版本,在相同的架构上(都是64位PowerShell v5.1.14393.1198)。 - Richard Ryszka
2个回答

9
我猜这可能是PowerShell.exe本身的问题,我可以在PowerShell 2.0、3.0、4.0和5.0中重现此问题。
如果你在使用PowerShell.exe运行脚本时没有运行任何其他命令,则无法使用Microsoft.PowerShell.Commands命名空间的类型约束,这是一个问题。
我为你找到了两个解决方法。
a. 在脚本开头运行一个无意义的cmdlet,例如:
Start-Sleep -Milliseconds 1
function Test-RestMethod {
param([string]$Uri, [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get')

$result = Invoke-RestMethod $uri -Method $Method
return $result
}

Test-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ -Method 'Get' | Format-Table -Property Title, pubDate
b. 去掉类型约束,仍然可以正常工作
function Test-RestMethod {
param([string]$Uri, $Method = 'Get')

$result = Invoke-RestMethod $uri -Method $Method
return $result
}

Test-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ -Method 'Get' | Format-Table -Property Title, pubDate

4
是的,你的解决方法对我有用,并帮助我找到了实际问题所在。异常是由于未加载/导入PowerShell模块Microsoft.PowerShell.Utility引起的。在你提供的第一个解决方法中运行Start-Sleep会静默地加载此模块,但我不知道为什么它会以这种方式工作。我将在另一个答案中描述这个问题。 - Richard Ryszka
我知道这篇文章很旧,但我最近才遇到了这个问题(使用PowerShell 7)。根据您关于名称空间“惰性加载”的逻辑,那么将引用名称空间中的枚举的代码行也包装在Measure-Command块中应该也可以工作。我将尝试这个修复(hack)来看看它是否有效。 - Glen

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接