无法获取返回值

时间:2019-01-28 15:55:01

标签: powershell powershell-v3.0

以下代码段未产生我需要的输出。

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

假设输入为Microsoft CorpSoftware Eng

$companyNameandPosition的输出为System.Object[]_System.Object[]

我阅读了这个SO page和这个Microsoft Docs页面,但似乎无法正常运行。

预期输出为microsoft_corp_software_eng.odt

1 个答案:

答案 0 :(得分:0)

在您的函数中,两个对象被馈送到管道:return语句中的$cleanString.Replace(" ", "_")$cleanString。顺便说一下,$ cleanstring不会更改。

用于替换,降低和修剪等操作的步骤很多,可以合并为一个语句。我改变了一些东西:

# 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