我是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
所以它会导出但只有部分结果。
错误 - 方法调用失败,因为[System.Management.Automation.PSObject]不包含名为“op_Addition”的方法。
答案 0 :(得分:11)
如果Import-Csv
仅返回1个结果,那么您认为您的变量不是数组是正确的,那么连接将失败。您使用@()
预先初始化变量这一事实并未改变。事实上,这一步是没有必要的。
要强制将结果视为数组,您可以将整个Import-Csv
行包装在@()
中,或者之后执行类似的操作。
$new = @( Import-Csv $File | Where-Object {...} )
# or
$new = Import-Csv $File | Where-Object {...}
$new = @($new)
答案 1 :(得分:1)
所以你要导入相同的CSV文件3次?导入一次然后将数组设置为过滤“视图”是不是更好?
有点像这样。您还应该能够使用每个数组中的“Count”值来说明是否返回了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
[array]$New
[array]$Term
[array]$Procd
[array]$Import = Import-Csv $File
[array]$New = $Import | ? {$_.TermDate -eq "" -and $_.LastName -ne "" -and $_.Processdate -eq ""}
[array]$Term = $Import | ? {$_.TermDate -ne "" -and $_.Processdate -eq "" -and $_.TermDate -le $e}
[array]$Procd = $Import | ? {$_.Processdate -ne ""}
#Process both new and term users provided there are records to process for each
if (($New.Count -gt 0) -and ($Term.Count -gt 0))
{
# Some code to process users
}
$new += $term
$new += $Procd
$new | Export-Csv $file -NoTypeInformation -ErrorAction SilentlyContinue
答案 2 :(得分:0)
您还可以通过对变量进行类型转换来强制执行该类型:
$array = @()
$array = gci test.txt
$array.GetType()
[array]$array = @()
$array = gci test.txt
$array.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True FileInfo System.IO.FileSystemInfo
True True Object [] System.Array
答案 3 :(得分:0)
我知道我迟到了这个讨论,但对于其他人来说...... 由于您已将$ new定义为空数组,因此当您从csv导入时要将输出添加到预定义数组时,不要将其设置为等于import-csv的输出。
$new = @()
$new += Import-Csv $File | Where-Object {
$_.TermDate -eq "" -and $_.LastName -ne "" -and $_.Processdate -eq ""
}