Brian Lyttle
Brian Lyttle

Reputation: 14579

How do I do a string replacement in a PowerShell function?

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.

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://", "")

Upvotes: 19

Views: 54742

Answers (4)

Steven Murawski
Steven Murawski

Reputation: 11255

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.

PowerShell does have a replace operator, so you could make your function into

function CleanUrl($url)
{
    return $url -replace 'http://'
}

Upvotes: 16

Jaykul
Jaykul

Reputation: 15824

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).

You should, however, use .Replace() unless you need the extra feature(s) of -replace (it handles regular expressions, etc).

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:

$HostHeader = "http://google.com"
$SiteName = CleanUrl $HostHeader
Write-Host $SiteName

Hope that helps. By the way, to demonstrate $input:

function CleanUrls
{
    $input -replace "http://",""
}

# Notice these are arrays ...
$HostHeaders = @("http://google.com","http://stackoverflow.com")
$SiteNames = $HostHeader | CleanUrls
Write-Output $SiteNames

Upvotes: 19

EBGreen
EBGreen

Reputation: 37740

This worked for me:

function CleanUrl($input)
{
    return $input.Replace("http://", "")
}

Upvotes: -4

ESV
ESV

Reputation: 7730

function CleanUrl([string] $url)
{
    return $url.Replace("http://", "")
}

Upvotes: 5

Related Questions