string 如何在 PowerShell 函数中进行字符串替换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I do a string replacement in a PowerShell function?
提问by Brian Lyttle
How do I convert function input parameters to the right type?
如何将函数输入参数转换为正确的类型?
I want to return a string that has part of the URL passed into it removed.
我想返回一个字符串,其中删除了传递给它的 URL 的一部分。
This works, but it uses a hard-coded string:
这有效,但它使用硬编码字符串:
function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
This fails:
这失败了:
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://", "")
采纳答案by Steven Murawski
The concept here is correct.
这里的概念是正确的。
The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.
问题在于您选择的变量名称。$input 是 PowerShell 用来表示管道输入数组的保留变量。如果你改变你的变量名,你应该没有任何问题。
PowerShell does have a replace operator, so you could make your function into
PowerShell 确实有一个替换运算符,因此您可以将您的函数转换为
function CleanUrl($url)
{
return $url -replace 'http://'
}
回答by Jaykul
Steve's answer works. The problem with your attempt to reproduce ESV's script is that you're using $input
, which is a reserved variable (it automatically collects multiple piped input into a single variable).
史蒂夫的回答有效。您尝试重现 ESV 脚本的问题在于您正在使用$input
,它是一个保留变量(它会自动将多个管道输入收集到一个变量中)。
You should, however, use .Replace() unless you need the extra feature(s) of -replace (it handles regular expressions, etc).
但是,您应该使用 .Replace() ,除非您需要 -replace 的额外功能(它处理正则表达式等)。
function CleanUrl([string]$url)
{
$url.Replace("http://","")
}
That will work, but so would:
这会起作用,但也会:
function CleanUrl([string]$url)
{
$url -replace "http://",""
}
Also, when you invoke a PowerShell function, don't use parenthesis:
此外,当您调用 PowerShell 函数时,不要使用括号:
$HostHeader = "http://google.com"
$SiteName = CleanUrl $HostHeader
Write-Host $SiteName
Hope that helps. By the way, to demonstrate $input:
希望有帮助。顺便说一下,为了演示 $input:
function CleanUrls
{
$input -replace "http://",""
}
# Notice these are arrays ...
$HostHeaders = @("http://google.com","http://stackoverflow.com")
$SiteNames = $HostHeader | CleanUrls
Write-Output $SiteNames
回答by ESV
function CleanUrl([string] $url)
{
return $url.Replace("http://", "")
}
回答by EBGreen
This worked for me:
这对我有用:
function CleanUrl($input)
{
return $input.Replace("http://", "")
}