我是 powershell 的新手,需要帮助。我的第一个工作脚本是自动化 AD 环境中的新用户和术语用户。
我们的 Peoplesoft 系统每天都会进行一次 CSV 转储。我用 Import-CSV
并创建 3 个数组(新的、术语和已处理的)。
我遇到的麻烦是在我遍历所有用户并尝试将其放回文件后组合 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
所以它会导出但只有部分结果。
error - Method invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'.
最佳答案
如 Import-Csv
只返回 1 个结果,那么您认为您的变量不是数组是正确的,那么连接将失败。这不会因为您已使用 @()
预初始化变量而改变。 .事实上,这一步是没有必要的。
要强制将结果视为数组,您可以将整个 Import-Csv
包裹起来。线在 @()
,或之后做类似的事情。
$new = @( Import-Csv $File | Where-Object {...} )
# or
$new = Import-Csv $File | Where-Object {...}
$new = @($new)
关于arrays - Powershell - 组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14903970/