powershell - 在 Powershell 中修改现有 CSV 文件

标签 powershell csv powershell-3.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 的好方法。

最佳答案

首先,这是显而易见的,但无论如何让我声明一下。第一次运行此脚本时,$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

关于powershell - 在 Powershell 中修改现有 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233226/

相关文章:

双击启动 Powershell 脚本时不起作用

powershell - Powershell命令仅在我在ise中运行选择时有效

arrays - 比较2个数组并删除元素

powershell - 在powershell中按CPU使用百分比列出进程

powershell - TFS 2017 vNext Build使用Powershell获得工作空间

linux - 如何从 Bash 将配对数字列表导出到 .csv 文件?

mysql - 无法将 CSV 加载到 MySQL -(OS errno 13 - 权限被拒绝)

git - 分支名称不符合git标准:refs/heads/master

powershell - 当函数在 ValueFromPipelineByPropertyName 参数的管道中没有发出任何输出时,管道输入不会被验证

sql - 将 csv 文件导入/复制到 PostgreSQL |文件不在本地服务器上