我从Active Directory获得了一个csv导出,如下所示:
Name,"GivenName","Surname","Department","LogonWorkstations" jdoe,"John","Doe","Finance","pc1" fbueller,"Ferris","Bueller","Sales","pc2"
现在我想在每个Workstation上搜索,检查文件夹是否存在并将该信息写回csv。
$input
正如您在代码中看到的,Add-Member将附加信息添加到{{1}},但是在将其导出到csv后,该信息不可用。
答案 0 :(得分:2)
有效。问题在于If条件。
$input = Import-Csv "C:\Scripts\input.csv"
ForEach ($line in $input) {
Add-Member -InputObject $line -NotePropertyName "xyz" -NotePropertyValue "exists"
}
$input # here I get the information
$input | Export-Csv "C:\Scripts\output.csv" -NoTypeInformation -Encoding Unicode
我建议将Add-Member
调用作为第一个命令移动到循环中,使用默认值(可能为空),然后在条件中设置值。
ForEach ($line in $input)
{
Add-Member -InputObject $line -NotePropertyName "xyz" -NotePropertyValue $null
$wst = $line.LogonWorkstations
If ($wst -ne "")
{
If (Test-Connection $wst -Count 1 -Quiet -ErrorAction SilentlyContinue)
{
If (Test-Path "\\$wst\c$\Program Files\xyz" -ErrorAction SilentlyContinue)
{
$line.xyz = 'exists'
}
}
}
}
答案 1 :(得分:1)
您将新成员添加到变量$line
并期望将其写回$input
..但不是。
试试这个:
$input = Import-Csv "C:\Scripts\input.csv"
$counter=0
ForEach ($line in $input) {
$wst = $line.LogonWorkstations
If ($wst -ne "") {
If (-not ( Test-Connection $wst -Count 1 -Quiet -ErrorAction SilentlyContinue)) {
If (-not (Test-Path "\\$wst\c$\Program Files\xyz" -ErrorAction SilentlyContinue)) {
Add-Member -InputObject $input[$counter] -NotePropertyName "xyz" -NotePropertyValue "exists"
}
}
}
$counter++
}
$input # here I get the information
$input | Export-Csv "C:\Scripts\output.csv" -NoTypeInformation -Encoding Unicode
我更改了InputObject
- 参数,将新成员写入input
变量。
答案 2 :(得分:0)
我建议使用calculated property进行此类修改:
Import-Csv "C:\Scripts\input.csv" |
Select-Object *, @{n='xyz';e={
$wst = $_.LogonWorkstations
if ($wst) {
if (Test-Connection $wst -Count 1 -Quiet -EA SilentlyContinue) {
$path = "\\$wst\c$\Program Files\xyz"
[bool](Test-Path $path -EA SilentlyContinue)
}
}
}} |
Export-Csv 'C:\Scripts\output.csv' -NoType -Encoding Unicode