无法将值“年”转换为类型“ System.Int32”。错误:“输入字符串的格式不正确。”

时间:2018-06-25 14:17:04

标签: powershell

代码-

# Get current Year and Month
param ([Int]$Year, [Int]$Month, [String]$Environment, [String]$Report, [String]$Username, [String]$Password)

function Get-DaysOfMonth {
    Param ([Int]$Year, [Int]$Month)
    $MonthDays = New-Object System.Collections.Generic.List[System.Object]
    1..([datetime]::DaysInMonth($Year, $Month)) |
        ForEach-Object {
           $Day = ([datetime]::ParseExact("$_/$Month/$Year", "d/M/yyyy", [System.Globalization.CultureInfo]::InvariantCulture)).ToString("dd")
           $MonthDays.Add($Day)
        }
    return $MonthDays
}

Write-Host "The Year Selected is: " + [String]$Year
Write-Host "The Month Selected is: " + [String]$Month
Write-Host "The Environment Selected is: $Environment"
Write-Host "The Report Generated is: $Report"
Write-Host "Export Generating as User: $Username"

$Days = Get-DaysOfMonth -Year $Year -Month $Month

运行时,我得到以下回溯:

Cannot process argument 
transformation on parameter 'Year'. Cannot convert value "Year" to type 
"System.Int32". Error: "Input string was not in a correct format."
    + CategoryInfo          : InvalidData: (:) [myscript.ps1], ParentContai 
   nsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,myscript 
   .ps1

似乎在将我的Integer变量转换为String时遇到问题。我该如何解决?

我正在通过以下命令运行脚本

myscript.ps1 -Year 2018 -Month 02 -Environment PROD -Report event -Username myacct -Password mypass

1 个答案:

答案 0 :(得分:1)

您的Write-Host命令仍然存在问题。

它在这里运行,但输出:

The Year Selected is:  + [String]2018
The Month Selected is:  + [String]2
The Environment Selected is: PROD
The Report Generated is: event
Export Generating as User: myacct

解决此问题的一种方法是使用字符串格式运算符:

"The Year Selected is: {0}`nThe Month Selected is: {1}`nThe Environment Selected is: {2}`nThe Report Generated is: {3}`nExport Generating as User: {4}" -f $Year,$Month,$Environment,$Report,$Username

The Year Selected is: 2018
The Month Selected is: 2
The Environment Selected is: PROD
The Report Generated is: event
Export Generating as User: myacct