用返回的变量替换单元格的值时遇到问题-格式不正确?

问题描述

我目前正在为代码中的某些细节而苦苦挣扎。

我有一个SQL查询,该查询在Powershell中运行,可以正常工作,并将数据转储到CSV中-一切正常。 然后,我将这些数据导入Powershell。

$csv = Import-Csv -Path "$Path" | where {$_.Fullname -ne "System created."} #this filtering is done to sort incosistent data.

然后我实际上正在挣扎,因为我正在进行一些检查,并想用管理员的ID替换用户的PIN码。

Write-Host "initializing loop to go through each element"
 foreach ($row in $csv)
    {
    if(($row.primarypin.length -lt 1) -or ($row.primarypin.length -gt 5) -or ($row.primarypin -contains 'T') -or ($row.primarypin -contains 'X'))
        {
         Write-Host "Doing Primary Check" -BackgroundColor Green
         Write-Host $row.primarypin.Length
         Write-Host $row.FullName
         try{
         $getTempuserUsername = $row.name
         Write-Host "Replacing UserID with their Manager" -ForegroundColor magenta -BackgroundColor Cyan
         $getUsersManager = Get-ADUser -identity $getTempuserUsername -Properties department,Manager | Select-Object Manager
         Write-Host "Replacing with String $getUsersManager"
         $row.primarypin = $null
         $row.primarypin -replace $null,$getUsersManager
         }
         catch{
            Write-Host "Replacing With a Cannot find User in AD" -ForegroundColor Yellow -BackgroundColor Red
            $row.primarypin -replace "Cannnot find user,this is a system user."
         }
         }
   else
        {
            Write-Host "Went directly to the else loop" -ForegroundColor red -BackgroundColor Yellow
            foreach($dataset in $row)
            {
                Write-Host "$dataset"

            }
        }
    }

这里的问题是,每当我尝试进行替换时,它似乎确实在控制台中替换了它,但是似乎并没有正确地将其保存到CSV文件中(我正在将其邮寄,但是已经正确地获得了该部分)。

Remove-Item $path
$csv | Export-Csv -Path $path -NoTypeinformation -NoClobber

所以每次我返回数据集时,它都会返回为

"@{name=adnameexample; FullName=Lastname,Firstname; ColourCost=0.21600; Colour Pages Printed=13; primarypin=; Office=London; Department Number=}"

在这种情况下,我希望将主销作为经理的ID返回。 (我还尝试使用try / catch,以防出现问题。

有人知道如何替换特定单元格中的数据吗?

向导,请帮助我!

解决方法

首先,此命令返回一个具有manager属性的对象

$getUsersManager = Get-ADUser -identity $getTempUserUsername -Properties department,Manager | Select-Object Manager

似乎您只需要该值,因此将-Expandproperty添加到Select-Object命令中。只要确保您知道,它将是一个专有名称。如果只需要名称,则需要查找管理器或使用正则表达式将其提取。另外,如果不使用部门属性,为什么还要拉它呢?新行可能看起来像

$getUsersManager = Get-ADUser -identity $getTempUserUsername -Properties Manager | Select-Object -Expandproperty Manager

仅从专有名称中提取名称是一种方法。

$getUsersManager = $getUsersManager -replace '^.*?=(.*?),[a-z]{2}=.*$','$1'

接下来,当您执行替换操作时,还需要将其设置回主引脚。我会将集合删除为$null,然后只用管理器替换其中的任何内容(即使没有内容)。

$row.primarypin = $row.primarypin -replace '.+',$getUsersManager