在Powershell中修改现有CSV文件

时间:2013-10-07 19:42:08

标签: powershell csv powershell-v3.0 export-to-csv

我设置了一个脚本,用于将用户的Exchange邮箱迁移到.pst文件中。我的想法是,我将有一个CSV文件,我可以将用户的名字打开,然后当脚本每晚开始时,它将打开CSV文件并查找已添加的用户,对这些用户帐户执行请求的操作(导出) ,移动设置权限等)然后写回CSV文件将这些用户标记为已完成并写入完成日期。这是我到目前为止所拥有的。

$InPstPath = '\\server1\PST_Store\'
$OutPstPath = '\\server2\PST_Store\'
$User = Get-Content $OutPstPath'login.txt'
$PWord = cat $OutPstPath'pass.txt' | convertto-securestring
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
$PSSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Server1/powershell -Credential $Credentials
Import-PSSession $PSSession
$In_List = Invoke-Command {Import-Csv "\\Server1\PST_Store\Admin\To_Be_Exported.csv"} -computername Server1 -Credential $Credentials
foreach ($objUser in $In_List) {
    if ($objUser.Completed -ne "Yes") {
        $TargetUser = $objUser.name
        $ShortDate = (Get-Date).toshortdatestring()
        New-MailboxExportRequest -Mailbox $TargetUser -Filepath "$InPstPath$TargetUser.pst"
        $objUser.Completed = "Yes"
        $objUser.Date = $ShortDate
        }
    }
Remove-PSSession -Session (Get-PSSession)

我无法找到将$ objUser.Completed和$ objUser.Date值写回CSV的好方法。

1 个答案:

答案 0 :(得分:2)

首先,这很明显,但无论如何我都要陈述一下。第一次运行此脚本时,$ objUser.name,$ objUser.Completed和$ objUser.Date将不存在;那么,行

$TargetUser=$objUser.name

将无法正常工作,除非您在该csv中实际具有该结构(即具有标题名称,已完成,日期)。

现在假设你完成了那部分,你所要做的就是创建一个捕获对象状态然后再写回来的对象。

$Processed = foreach ($objUser in $In_List) {
    if ($objUser.Completed -ne "Yes") {
        $TargetUser = $objUser.name
        $ShortDate = (Get-Date).toshortdatestring()
        New-MailboxExportRequest -Mailbox $TargetUser -Filepath "$InPstPath$TargetUser.pst"

        [PSCustomObject]@{Name=$objUser.name;Completed="Yes";Date=$ShortDate}
        }
    } else {
        [PSCustomObject]@{Name=$objUser.name;Completed="No";Date=$null}
    }
## export to a temp file
$Processed | export-csv -Path $env:TEMP\processed.csv
## You should probably check to see if original file was modified since you started working on it
# and copy over if not
Copy-Item $env:TEMP\processed.csv $OutPstPath'login.txt' -force