带命名参数的PowerShell脚本字符串插值无效
我有以下功能(我只是将其粘贴到命令行中): 然后我称之为:带命名参数的PowerShell脚本字符串插值无效,powershell,string-interpolation,Powershell,String Interpolation,我有以下功能(我只是将其粘贴到命令行中): 然后我称之为: Test("localhost:90", "IService", "TestMethod") 我得到: http://localhost:90 IService TestMethod// 我希望得到: http://localhost:90/IService/TestMethod 如果我首先将结果设置为变量,也会发生同样的情况: $res = "http://$url/$interface/$method" Write-Host
Test("localhost:90", "IService", "TestMethod")
我得到:
http://localhost:90 IService TestMethod//
我希望得到:
http://localhost:90/IService/TestMethod
如果我首先将结果设置为变量,也会发生同样的情况:
$res = "http://$url/$interface/$method"
Write-Host $res
我也不认为这是由于Write Host
,因为如果我将此字符串传递到.NET对象中,会出现相同的错误
如果我只定义每个变量,这会让我完全困惑。所以,这与这些是函数参数这一事实有关。我可以从命令行执行此操作:
function Test ($url, $interface, $method)
{
Write-Host "http://$url/$interface/$method"
}
PS C:\> $url = "localhost:90"
PS C:\> $interface = "IService"
PS C:\> $method = "TestMethod"
PS C:\> Write-Host "http://$url/$interface/$method"
http://localhost:90/IService/TestMethod
PS C:\>
我是在做傻事,还是有其他方法在PowerShell中进行字符串插值?你没有做傻事,但你将PowerShell与Python之类的东西混为一谈 当我这样做时:
Function Count-Args
{
$args.count
}
Count-args($var1, $var2, $var3)
我得到一个1的计数,并且您放入()
的所有三个变量都被转换为一个数组,转换为$args
只需将调用函数的方式更改为test mysite myinterface mymethod
。请注意
您甚至不需要创建一个param块,如果您保留原始函数,只需像我的示例底部那样分隔参数,它就可以工作了。这类基本的东西总是让我进入PowerShell。你可能会从一本介绍PowerShell的书中获益匪浅,这里的所有内容都是一个常见的实践问题。PowerShell.org有很多不错的免费学习PS的电子书。酷,我来看看!
Don't add brackets around the function parameters:
$result = Add-Numbers (5, 10) --Wrong!
$result = Add-Numbers 5 10 --Right