使用ExportTo-Csv cmdlet时会丢弃前导零

时间:2016-05-03 10:28:21

标签: csv powershell

以下是我正在运行的脚本。

脚本运行正常。它提供了适当的输出,但它正在从几列中删除前导零。请建议如何保留整数字段的前导零。

我正在使用

$res.data.Tables[0] | ConvertTo-Csv -NoType | ForEach-Object {$_.Replace('"','')} | Out-file $fileName -Force"

用于将数据导出到CSV文件。请建议如何保留前导零(至少2位小数)。

param([int]$accountingDay = 1, [string]$outputFolder)

$server = "ADMSQL01"
$db = "cc111db"

function exec-storedprocedure($storedProcName,
        [hashtable] $parameters=@{},
        [hashtable] $outparams=@{},
        $conn) {

    function put-outputparameters($cmd, $outparams) {
        foreach ($outp in $outparams.Keys) {
            $p = $cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])) 
            $p.Direction=[System.Data.ParameterDirection]::Output
            $p.Size=4
        }

    }
    function get-outputparameters($cmd,$outparams){
        foreach ($p in $cmd.Parameters) {
            if ($p.Direction -eq [System.Data.ParameterDirection]::Output) {
                $outparams[$p.ParameterName.Replace("@","")]=$p.Value
            }
        }
    }

    function get-paramtype($typename) {
        switch ($typename) {
            'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
            'int' {[System.Data.SqlDbType]::Int}
            'xml' {[System.Data.SqlDbType]::Xml}
            'nvarchar' {[System.Data.SqlDbType]::NVarchar}
            default {[System.Data.SqlDbType]::Varchar}
        }
    }

    $close = ($conn.State -eq [System.Data.ConnectionState]'Closed')
    if ($close) {
        $conn.Open()
    }

    $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
    $cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
    $cmd.CommandText = $storedProcName
    foreach ($p in $parameters.Keys) {
        $cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction = [System.Data.ParameterDirection]::Input
    }

    put-outputparameters $cmd $outparams
    $ds = New-Object System.Data.DataSet
    $da = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
    [Void]$da.fill($ds)
    if ($close) {
        $conn.Close()
    }
    get-outputparameters $cmd $outparams

    return @{data=$ds;outputparams=$outparams}
}

# setup the 'framework' to use PowerShell with SQL 
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection

# SQL Server connection string
$sqlConnection.ConnectionString = $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db 

# execute stored procedure
$res=exec-storedprocedure -storedProcName 'sp_OPTUS_summary' -parameters @{inAccountFieldValues=$null;inAccountViewID=1;inAccountLevel=4;inAccountingDay=$accountingDay;inAccountPeriod=3;inUserGroupID=2} -outparams @{} $sqlConnection  

if ($res.data.Tables.Count) {
    # store results in file
    $curYear = Get-Date -Format yyyy
    $curMonth = Get-Date -Format MMM
    $curTime = (Get-Date -Format s).Replace(':', ' ')
    $fileName = $outputFolder + '\scheduled-' + $curYear + '-' + $curMonth + '-' + $accountingDay + '-' + $curTime + '.csv'
    $res.data.Tables[0] | ConvertTo-Csv -NoType | ForEach-Object {$_.Replace('"','')} | Out-File $fileName -Force
}

1 个答案:

答案 0 :(得分:2)

整数没有“前导零”。如果要导出格式化输出,则需要将相应字段转换为格式化字符串,例如像这样:

$res.data.Tables[0] |
  Select-Object FieldA, FieldB, @{n='FieldC';e={'{0:d2}' -f $_.FieldC}},
                @{n='FieldD';e={'{0:d2}' -f $_.FieldD}}, FieldE, ... |
  ConvertTo-Csv -NoType |
  ...