2017-07-26 15 views
0

各行の上にNewtonSoft JSONアノテーションを挿入するPowerShellスクリプトを作成しました。正しくないC#モデルの配列の文字列を置き換えます

public class Rootobject 
{ 
    public string clientID { get; set; } 
    public string bankID { get; set; } 
    public string applicationID { get; set; } 
    //(...) 
    public string appName { get; set; } 
    public GeneralData loanDataRequest { get; set; } 
} 

public class Roles 
{ 
    public string role1 { get; set; } 
    public string otherParty1 { get; set; } 
} 

結果ファイル:

public class Rootobject  
{ 

[JsonProperty(PropertyName = "")] 
public string clientID { get; set; } 

[JsonProperty(PropertyName = "")] 
public string bankID { get; set; } 

[JsonProperty(PropertyName = "")]   
public string applicationID { get; set; } 
... 
} 
//other properties are exluded due to simplicity of the code 

スクリプト:私はなりたい

$FileName = "E:\startingFile.txt" 
$FileOriginal = Get-Content $FileName 
$lines = (Get-Content E:\startingFile.txt) 
#trim lines 
$newcontent = foreach ($line in $lines) { 
    $line.Trim() 
} 

for ($i = 0; $i -lt $FileOriginal.Length; $i++) { 
    if ($FileOriginal[$i] -like "*public*" -and $FileOriginal[$i] -notlike "*class*") { 
     # insert your line before this line and not insert if line contains '{','}' 
     $FileOriginal[$i] -replace 'public', '`npublic' 
     $FileOriginal[$i] -replace '{', '`n{' 
     $NewFileContent += "`n[JsonProperty(PropertyName = """ + $FileOriginal[$i].Split()[2] + """)]" 
    } 

    $NewFileContent += $FileOriginal[$i] 
} 

$NewFileContent | Out-File "E:\resultFile.txt" 

結果ファイル:

ファイルを起動する

public class Rootobject  
{ 

    [JsonProperty(PropertyName = "clientID ")] 
    public string ClientID { get; set; } 

    [JsonProperty(PropertyName = "bankID ")] 
    public string BankID { get; set; } 

    [JsonProperty(PropertyName = "applicationID ")]   
    public string ApplicationID { get; set; } 
    ... 
} 
//other properties are exluded due to simplicity of the code 

質問:

  1. なぜそれが私のJSONのPropertyNameに$FileOriginal[$i].Split()[2]を追加していないのだろうか?

    Answer(editied):私の行には複数の空白が含まれていることがわかりましたので、今のところ私は$FileOriginal[$i].Split()[10]のような値を得ることができます。

  2. 私の配列$lines[3]の代わりに、最初の文字を大文字にするには? (public string clientID - >public string ClientID

  3. 私のtxt出力を正しくフォーマットする方法は、startingFileとまったく同じですか?

答えて

1

配列に要素を挿入したり、出力文字列を作成したりしないでください。出力ストリームに新しい行を挿入するだけです。また、インデントを保持する場合は、先頭の空白を削除しないでください。

Get-Content 'E:\startingFile.txt' | ForEach-Object { 
    if ($_ -like '*public*' -and $_ -notlike '*class*') { 
     if ($_ -match '^(\s*)(public\s+\w+\s+)(\w)(\w*)(.*)') { 
      '{0}[JsonProperty(PropertyName = "{1}{2}")]' -f $matches[1,3,4] 
      $_ = '{0}{1}{2}{3}{4}' -f $matches[1], $matches[2], $matches[3].ToUpper(), $matches[4], $matches[5] 
     } 
    } 
    $_ 
} | Set-Content 'E:\resultFile.txt' 
関連する問題