I want to find a function in a c# file and make some changes in the body with powershell. I've read this page and I didn't understand.
答案 0 :(得分:0)
下面的代码找到一个c#文件并返回一个CodeElement对象,在其中可以操纵函数体,参数,属性等。
#Find the file
function global:GetFile { param($Project,[string]$Path)
$result = $false
$directories = $Path -split '\\'
if($directories[0]) {
for($i=0;$i -lt $directories.count;$i++) {
if(($Project).ProjectItems) {
$Project = ($Project).ProjectItems | Where-Object { $_.Name -eq $directories[$i]}
}
}
if(!$Project)
{ write-host "File not found" }
else
{ $result = $Project }
}
return $result
}
#Find the function
function global:GetFunctionAsCM {
param([object] $Project,[string] $Path,[string] $rootnamespaceSpace,[string]$partialFileName=$null)
$file = GetFile -Project $Project -Path $Path
$namespaceParts = $rootnamespaceSpace.Split(".")
$codeModel = $file.ContainingProject.CodeModel
$rootnamespace = $namespaceParts[0]
for($i = 0; $i -lt $namespaceParts.Length;$i++) {
if ($codeModel.Kind -eq $null) {
$codeModel = $CodeModel.CodeElements | Where-Object {$_.FullName -eq $rootnamespace}
} elseif ($codeModel.Kind -eq [EnvDTE.vsCMElement]::vsCMElementNamespace) {
$codeModel = $CodeModel.Members | Where-Object {$_.FullName -eq $rootnamespace}
} elseif ($codeModel.Kind -eq [EnvDTE.vsCMElement]::vsCMElementClass) {
if($partialFileName -ne $null -and $codeModel.Parts.length>1) {
$codeModel = $codeModel.Parts | Where-Object {$_.ProjectItem.Name -eq $partialFileName}
}
$codeModel = $codeModel.Children | Where-Object {$_.FullName -eq $rootnamespace}
}
$rootnamespace = "$rootnamespace." + $namespaceParts[$i+1]
}
return $codeModel
}