string - 如何在PowerShell函数中进行字符串替换?

标签 string powershell function replace

如何将函数输入参数转换为正确的类型?

我想返回一个字符串,其中删除了传递给它的部分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/

相关文章:

c++ - 在 C++ 中格式化字符串是否与 Java 5/6 中的 String.format() 一样方便?

c - 使用 strcmp 搜索相等的字符串

powershell - Get-WinEvent 中消息的 grep 字符串

php - 如何处理 PHP 中 file_get_contents() 函数的警告?

sql - 使用 PostgreSQL 地理类型函数的问题 - PostGIS(扩展)

ruby - 为什么 Ruby String#split 不将连续的尾随定界符视为单独的实体?

regex - 什么时候最好在基本的字符串拆分/子字符串化上使用正则表达式?

Powershell 脚本在 Windows 8 上运行良好,但在 Windows 7 上运行不佳

azure - PowerShell 脚本用于在 azure 容器注册表上保留最新 10 个镜像,其余的需要删除

c# - 大量情况下的 Switch case 性能