【问题标题】:Powershell Script reading file into arrayPowershell脚本将文件读入数组
【发布时间】:2018-04-19 05:06:55
【问题描述】:

我正在编写一个脚本。我希望它在名为 ComputerName 的列和名为 UserName 的列中读取。

我的 CSV 文件如下所示:

ComputerName | Username
computer01   | user1
computer02   | user2

管道代表 Excel 中的单元格。

这是我的脚本:

$computerName = @()
$userName = @()

Import-Csv C:\test\script\Computername_username_test.csv -Delimiter "|" |`
    ForEach-Object
        {
            $computerName += $_.ComputerName
            $userName += $_.UserName
        }

$destination = New-Item -ItemType Directory -Path C:\test\$userName\dictionary_Files\ -force
$fileList = Get-WmiObject -Class CIM_DataFile -Filter "Drive='C:' And Extension='dic'" -Computername $computerName

foreach ($file in $fileList)
{
    $drive, $path = $file.Name.Split('\',2)
    $drive = $drive -replace ':','$'
    $remoteFile = "\\$computerName\$drive\$path"
    Write-Verbose "Copy $remoteFile to $destination"
    Copy-Item $remoteFile -Destination $destination -Confirm
}

我的目标是在远程计算机的 C 驱动器中搜索所有扩展名为 .dic 的文件,并将它们复制到与 Excel 表中的用户名相同的文件夹内的某个位置。

当我运行它时,我得到以下信息:

PS C:\Test\Script> C:\Test\Script\DicFiles03_importCSV.ps1
cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters:
Process[0]: 

            $computerName += $_.ComputerName
            $userName += $_.UserName

Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null, empty, or an element of the argument 
collection contains a null value. Supply a collection that does not contain any null values and then try the command again.
At C:\Test\Script\DicFiles03_importCSV.ps1:13 char:102
+ ...  -Filter "Drive='C:' And Extension='dic'" -Computername $computerName
+                                                             ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

感谢您的帮助。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我认为这是因为您在下一行的foreach-object 之后有您的{,powershell 是一种脚本语言,因此它特别关注行尾。

    【讨论】:

    • 好点,但是需要将命令放在同一行(有例外,以及使用显式续行的能力)不适用于整个语言,而仅适用于它的语言argument-mode 解析 - 参见 stackoverflow.com/a/49244654/45375
    • 感谢您的帮助,括号确实是问题所在。我对输出有一个新问题(当然)。现在,当它通过 CSV 运行时,它会将 $username 条目附加到一行中,因此第一个创建的目录是“user1”,第二个是“user1 user2”,依此类推。对不起,我是个菜鸟。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2014-09-24
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多