我有一个 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 尚未自动加载它,只需使用Import-Module或手动添加相应的模块或程序集Add-Type。在您的情况下,您必须加载可以从文档 ( Microsoft.PowerShell.Commands.WebRequestMethod) 派生的程序集:
Add-Type -AssemblyName Microsoft.PowerShell.Commands.Utility
Run Code Online (Sandbox Code Playgroud)