0

The following snippet isn't producing the output I need.

function replaceBlankSpacewithUnderscore
{             Param([Parameter(Mandatory=$true)]
               [string]$stringToClean)

    $cleanString = $stringToClean

    if($cleanString.Contains(" ")){
        $cleanString.Replace(" ", "_")
    }
    return $cleanString
}

# Prompt user for Company name
$companyName = Read-Host "Enter Company Name"

# Trim the string to make sure no leading or trailing whitespace exists
$companyName = $companyName.Trim()

# Prompt user for Position
$position = Read-Host "Enter Job Position"

# Trim the string to make sure no leading or trailing whitespace exists
$position = $position.Trim()

# Construct our new filename with the company name and position

# Company name to Lower Case
$companyNametoLowerCase = $companyName.ToLower()

# Position name to Lower Case
$positiontoLowerCase = $position.ToLower()

$companyNamewithUnderScores = replaceBlankSpacewithUnderscore -stringToClean $companyNametoLowerCase
$positionwithUnderScores = replaceBlankSpacewithUnderscore -stringToClean $positiontoLowerCase 

# Combine company name and position (lower case) into one string
$companyNameandPosition = [string]::Format("{0}_{1}", $companyNamewithUnderScores, $positionwithUnderScores)

Write-Output $companyNameandPosition

Suppose the input is Microsoft Corp and Software Eng.

The output of $companyNameandPosition is System.Object[]_System.Object[]

I read this SO page and this Microsoft Docs page, but I can't seem to get it working.

The expected output is microsoft_corp_software_eng.odt

1 Answers1

0

In your function two objects are fed to the pipeline: $cleanString.Replace(" ", "_") and $cleanString in the return statement. $cleanstring is not changed BTW.

There are a lot of steps used for operations like replace, tolower and trim that can be combined in one statement. I changed some things:

# Prompt user for Company name
$companyName = Read-Host "Enter Company Name"

# Prompt user for Position
$position = Read-Host "Enter Job Position"

# Combine company name and position (lower case) into one string
$companyNameandPosition = [string]::Format("{0}_{1}", $companyName.Replace(' ','_').ToLower().Trim(), $position.Replace(' ','_').ToLower().Trim())

Write-Output $companyNameandPosition