Powershell - 组合数组

use*_*056 5 arrays powershell

我是powershell的新手,需要帮助.我的第一个工作脚本是在AD环境中自动化新用户和用户.

我们的Peoplesoft系统每天都会进行一次CSV转储.我使用Import-CSV并创建了3个数组(new,term和processed).

我遇到的麻烦是,一旦我遍历所有用户并尝试将其放回文件中,就将3个阵列组合在一起.代码在行处断开$New += $Term.我相信这是因为我的测试文件中每个用户类型(新的,术语和已处理的)只有1条记录(我知道,添加更多用户......不能.这可能是任何现实世界的结果特别的一天).以下是我的示例代码:

#Get Credentials from user
$c = Get-Credential

#Get Date for $Term array population
$e = Get-Date -format M/d/yyyy

#Set file location and variable for said file
$File = "c:\users\nmaddux\desktop\adduserstuff\test.csv"

#Import record sets for New and Term users
$New   = @()
$Term  = @()
$Procd = @()
$New   = Import-Csv $File | Where-Object {
           $_.TermDate -eq "" -and $_.LastName -ne "" -and $_.Processdate -eq ""
         }
$Term  = Import-Csv $File | Where-Object {
           $_.TermDate -ne "" -and $_.Processdate -eq "" -and $_.TermDate -le $e
         }
$Procd = Import-Csv $File | Where-Object { $_.Processdate -ne "" }

#Process both new and term users provided there are records to process for each
If ($New -ne $NULL -and $Term -ne $NULL) {
  # Some code to process users
}

$new += $term
$new += $Procd
$new | Export-Csv $file -NoTypeInformation -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)

所以它会导出但只有部分结果.

error - 方法调用失败,因为[System.Management.Automation.PSObject]不包含名为"op_Addition"的方法.

lat*_*kin 11

如果Import-Csv只返回1个结果,那么你认为你的变量不是一个数组是正确的,那么连接就会失败.由于您已使用预先初始化变量,因此不会发生变化@().实际上,这一步是没有必要的.

要强制将结果视为数组,您可以将整Import-Csv行包装起来@(),或者之后执行类似的操作.

$new = @( Import-Csv $File | Where-Object {...} )
# or
$new = Import-Csv $File | Where-Object {...}
$new = @($new)
Run Code Online (Sandbox Code Playgroud)