运行powershell-命令时找不到类型

运行powershell-命令时找不到类型,powershell,bamboo,Powershell,Bamboo,我有一个PowerShell脚本,我打算用它作为部署步骤。打开PowerShell并使用/script.ps1运行脚本工作正常,但使用PowerShell.exe-command./script.ps1失败,出现错误无法找到类型[Microsoft.PowerShell.Commands.WebRequestMethod] 直接从PowerShell运行脚本与使用PowerShell.exe-command运行脚本之间有什么区别?我错过了什么 MWE对于所讨论的问题: function Test

我有一个PowerShell脚本,我打算用它作为部署步骤。打开PowerShell并使用
/script.ps1
运行脚本工作正常,但使用
PowerShell.exe-command./script.ps1
失败,出现错误
无法找到类型[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.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

我猜您的powershell路径将返回不同的版本,请尝试使用Get-Host确定每种方法使用的版本。它们都使用相同的版本,在相同的体系结构上(都是64位powershell v5.1.14393.1198)。是的,您的解决方法对我有效,它们帮助我找到了真正的问题所在。未加载/导入PowerShell模块Microsoft.PowerShell.Utility导致异常。在您的第一个解决方案中运行
Start Sleep
,可以安静地加载此模块,但我不知道为什么它会以这种方式工作。我将在另一个答案中对此进行描述。我知道这篇文章很旧,但我最近才遇到这个问题(使用PowerShell 7)。给定关于名称空间“延迟加载”的逻辑,那么在度量命令块中包装引用名称空间中的枚举的代码行也应该有效。我将尝试将此作为修复(黑客),看看它是否有效。