运行 powershell -command 时无法找到类型

Ric*_*zka 4 powershell bamboo

我有一个 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
Run Code Online (Sandbox Code Playgroud)

小智 5

我想这可能是 PowerShell.exe 本身的问题,我可以在 PowerShell 2.0、3.0、4.0 和 5.0 中重现该问题。

如果在使用 PowerShell.exe 运行脚本时不先运行任何其他命令,则无法使用命名空间 Microsoft.PowerShell.Commands 的类型约束,这是一个问题

我为您找到了两种解决方法。

一种。例如,在脚本的开头运行一个无意义的 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
Run Code Online (Sandbox Code Playgroud)

湾 删除类型约束,它仍然可以正常工作

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
Run Code Online (Sandbox Code Playgroud)

  • 是的,您的解决方法对我有用,它们帮助我找出真正的问题是什么。异常是由未加载/导入 PowerShell 模块“Microsoft.PowerShell.Utility”引起的。在第一个解决方法中运行“Start-Sleep”会安静地加载此模块,但我不知道为什么它会这样工作。我会在另一个答案中描述这一点。 (4认同)

sta*_*tor 4

要使类型可用,如果 PowerShell 尚未自动加载它,只需使用Import-Module或手动添加相应的模块或程序集Add-Type。在您的情况下,您必须加载可以从文档 ( Microsoft.PowerShell.Commands.WebRequestMethod) 派生的程序集:

Add-Type -AssemblyName Microsoft.PowerShell.Commands.Utility
Run Code Online (Sandbox Code Playgroud)