清理PowerShell命令

时间:2018-02-27 18:25:56

标签: powershell quest

我一直试图通过使其更清洁来重新格式化此命令,但我似乎无法绕过写入输出。

Get-QARSOperation -ParentContainer 'somedomain.com/OU1/OU2' -TargetObjectType 'user' |
  Where-Object {$_.Status -eq 'Completed' -and $_.Controls.ID -eq 'OperationReason'} |
  ForEach-Object {Get-QARSApprovalTask -Operation $_.ID} |
  ForEach-Object {
    Write-OutPut ("Target: " + $_.Operation.TargetObjectInfo.DN.Replace("CN=","").Replace("cn=","").Replace("\","").Replace(",","").Replace("OU","").Split('=')[0]);
    Write-OutPut ("Operation ID: "+ $_.Operation.ID);
    Write-OutPut ("Approver: " + $_.CompletedBy.DN.Replace("CN=","").Replace("\","").Replace(",","").Replace("OU","").Split('=')[0]);
    Write-OutPut ("StartedOn: " + $_.Created);
    Write-OutPut ("Completed: " + $_.Completed);
    Write-OutPut ("Comments: " + $_.CompletionReason);
    Write-OutPut ("Operation Type: " + $_.Operation.Type);
    Write-OutPut "" 
  }

我导出到csv时的格式也没有将数据放入列中。您有什么建议让这个脚本看起来更整洁?

谢谢!

1 个答案:

答案 0 :(得分:1)

正如评论中所建议的那样,正确的做法是使用Export-Csv生成CSV文件。至于创建一个要导出的对象并使其易于在代码中阅读,您可以执行类似于您拥有的操作,并使用它创建一个自定义对象,然后可以将其传送到Export-Csv。另外,我认为您的整个.Replace("CN=","").Replace("cn=","").Replace("\","").Replace(",","").Replace("OU","").Split('=')[0]可以简化为.Split('=,')[1]。字符串的.Split()方法接受多个要拆分的字符,它将在提供的任何字符上拆分。以下是我建议的内容,您需要在最后更新路径,如果我的工作不适合您,可能需要恢复更长的.Replace位。

Get-QARSOperation -ParentContainer 'somedomain.com/OU1/OU2' -TargetObjectType 'user' |
    Where-Object {$_.Status -eq 'Completed' -and $_.Controls.ID -eq 'OperationReason'} |
    ForEach-Object {Get-QARSApprovalTask -Operation $_.ID} |
    ForEach-Object {
        [PSCustomObject][Ordered]@{
            "Target" = $_.Operation.TargetObjectInfo.DN.Split('=,')[1]
            "Operation ID" = $_.Operation.ID
            "Approver" = $_.CompletedBy.DN.Split('=,')[1]
            "StartedOn" = $_.Created
            "Completed" = $_.Completed
            "Comments" = $_.CompletionReason
            "Operation Type" = $_.Operation.Type
        }
    } |
    Export-Csv C:\Path\To\File.csv -NoTypeInformation

您可以使用Select声明,但我认为这对您来说更清晰。