如何将函数输入参数转换为正确的类型?
我想返回一个字符串,其中删除了传递给它的部分URL。
可以,但是使用了硬编码的字符串:
function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
此操作失败:
function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
最佳答案
这里的概念是正确的。
问题在于您选择的变量名称。 $ input是PowerShell用来表示管道输入数组的保留变量。如果更改变量名,则应该没有任何问题。
PowerShell确实有a replace operator,因此您可以将函数设为
function CleanUrl($url)
{
return $url -replace 'http://'
}
关于string - 如何在PowerShell函数中进行字符串替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15062/