Arrays 将.csv拆分到阵列

Arrays 将.csv拆分到阵列,arrays,csv,powershell,Arrays,Csv,Powershell,我有一个包含2行信息的CSV文件。我想同时使用两者,但不是作为一个数组 在本例中,我的CSV如下所示: Name ;Computer user1 ;Comp1 user2 ;Comp2 user3 ;Comp3 user4 ;Comp4 我的目标是使用Computer和Name根据我的CSV中的值在广告中向计算机添加所有者。为了实现这一点,我觉得我需要将这些值拆分为2个数组,这样我就可以只针对每个循环使用split()函数。 这里有一些好信息: 但基本上: $demo = "abc ;def

我有一个包含2行信息的CSV文件。我想同时使用两者,但不是作为一个数组

在本例中,我的CSV如下所示:

Name ;Computer

user1 ;Comp1
user2 ;Comp2
user3 ;Comp3
user4 ;Comp4
我的目标是使用Computer和Name根据我的CSV中的值在广告中向计算机添加所有者。为了实现这一点,我觉得我需要将这些值拆分为2个数组,这样我就可以只针对每个循环使用
split()
函数。 这里有一些好信息: 但基本上:

$demo = "abc ;def"
$items = $demo.split(' ;')

您可以为CSV的每一列获取单独的数组,如下所示:

$csv = Import-Csv 'C:\path\to\your.csv'

$names     = $csv | Select-Object -Expand Name
$computers = $csv | Select-Object -Expand Computer

由于额外的空格,您的
CSV
文件似乎格式不正确。以下是初学者的解决方案:

阅读
Get Help'about_Split'-ShowWindow

$separator = " ;"            ### or $separator = " ", ";"
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$myFile = 'D:\bat\SO\34718014.csv'

ForEach ($strLine in Get-Content $myFile) {
    $asplit = $strLine.Split($separator, $option)
    if (($asplit[0] + $asplit[1] -ne "NameComputer") -and ($asplit[0] + $asplit[1] -ne $Null)) {
        '['+$asplit[0]+']['+$asplit[1]+']' #debug output
        #
        # place your code to add owner to computer in AD here
        #
    } else {
        "skipped line: " + $strLine # debug output: skipped CSV header, skipped empty line(s)
    }
}
对于修改后的Ansgar Wiechers的解决方案(无疑比我的初学者的解决方案更聪明),请阅读
获取帮助“导入Csv”-ShowWindow
。但是,它在
$Names
中保留额外的尾随空格:

Write-Host "Ansgar Wiechers' solution:"

$csv = Import-Csv 'D:\bat\SO\34718014.csv' -Delimiter ";"

$names     = $csv | Select-Object -Expand "Name "
$computers = $csv | Select-Object -Expand Computer

For ($i=0; $i -le $names.Count; $i++) {
    ('[' + $names[$i] + '][' + $computers[$i] + ']')
}
输出

PS D:\PShell> D:\PShell\SO\34718014.ps1
skipped line: Name ;Computer
skipped line: 
[user1][Comp1]
[user2][Comp2]
[user3][Comp3]
[user4][Comp4]
Ansgar Wiechers' solution:
[user1 ][Comp1]
[user2 ][Comp2]
[user3 ][Comp3]
[user4 ][Comp4]
[][]

我找到了我的问题的解决方案,因为我的列表已经完成,我将csv拆分为2个文件,并使用此代码完成了这项工作

$names = Get-Content Names.txt
$comp = Get-Content computers.txt

for($x=0; $x -lt $comp.length; $x++)
{
    Write-Host $comp[$x]
    Write-Host $names[$x]
    Get-ADComputer $comp[$x] -Properties * | Set-ADComputer -ManagedBy $names[$x]
}

你是说拥有电脑吗?或者你填充了其他值?