我能够打印出if..elseif..else的最终结果,如下所示:
clear-host
$errorCode = 0
$object = "InstanceName", "DatabaseName", "PrinicipalName", "PrinicipalType", "Permission", "ObjectTypeLevel", "ObjectName"
$logfile = "C:\temp\cep\gogo.csv"
$oldFile = "C:\temp\cep\Book1.csv"
$newFile = "C:\temp\cep\Book2.csv"
if ((Test-Path $oldFile) -And (Test-Path $newFile)) {
$impFileOld = Import-Csv $oldFile -Header $object | Sort-object -Property $object -unique
$impFileNew = Import-Csv $newFile -Header $object | Sort-object -Property $object -unique
$result = Compare-Object $impFileOld $impFileNew -Property $object -PassThru
$result | %{if ($_.SideIndicator -eq '=>') {write-host "book2"} #show result
elseif($_.SideIndicator -eq '<=') {write-host "book1"}
else {Add-Content $logfile "no changes found."
#$errorCode = 0
}
}
} else {
Add-Content $logfile "files does not exist!"
#$errorCode = 1
exit 1
};
但是当我用select-object替换它并将最终结果写入另一个.cvs文件时,似乎连接丢失了&#39;或通过infor:请在下面的代码:
clear-host
$errorCode = 0
$object = "InstanceName", "DatabaseName", "PrinicipalName", "PrinicipalType", "Permission", "ObjectTypeLevel", "ObjectName"
$logfile = "C:\temp\cep\gogo.csv"
$oldFile = "C:\temp\cep\Book1.csv"
$newFile = "C:\temp\cep\Book2.csv"
if ((Test-Path $oldFile) -And (Test-Path $newFile)) {
$impFileOld = Import-Csv $oldFile -Header $object | Sort-object -Property $object -unique
$impFileNew = Import-Csv $newFile -Header $object | Sort-object -Property $object -unique
$result = Compare-Object $impFileOld $impFileNew -Property $object -PassThru
$result | %{if ($_.SideIndicator -eq '=>') {Select-Object $object | export-csv $logfile -NoTypeInfo} #cannot print result to .csv file ????
elseif($_.SideIndicator -eq '<=') {Select-Object $object | export-csv $logfile -NoTypeInfo}
else {Add-Content $logfile "no changes found."
#$errorCode = 0
}
}
} else {
Add-Content $logfile "files does not exist!"
#$errorCode = 1
exit 1
};
答案 0 :(得分:0)
您的代码存在多个问题,而且不会让您受到攻击。
如果你提出一个简化版本:
cls
$object = "InstanceName", "DatabaseName", "PrinicipalName", "PrinicipalType", "Permission", "ObjectTypeLevel", "ObjectName"
$logfile = "C:\temp\cep\gogo.csv"
$oldFile = "C:\temp\cep\Book1.csv"
$newFile = "C:\temp\cep\Book2.csv"
if (!(Test-Path $oldFile) -Or !(Test-Path $newFile))
{
Add-Content $logfile "files does not exist!"
exit 1
}
$impFileOld = Import-Csv $oldFile -Header $object
$impFileNew = Import-Csv $newFile -Header $object
$result = Compare $impFileOld $impFileNew -Property $object
if ($result -eq $null)
{
Add-Content $logfile "no changes found."
}
else
{
$result | where SideIndicator -eq '=>' | select $object | sort $object | export-csv "C:\temp\cep\gogoBook2.csv" -NoType
$result | where SideIndicator -eq '<=' | select $object | sort $object | export-csv "C:\temp\cep\gogoBook1.csv" -NoType
}