【问题标题】:Import CSV issue powershell导入 CSV 问题 powershell
【发布时间】:2014-03-22 02:27:51
【问题描述】:

我正在编写一个脚本来自动添加用户。我想读取目录中的所有 CSV 文件,直到它们完成,然后我想将这些 csv 移动到存档中。在程序中,我正在检查一个 txt 文件以确保该程序的另一个实例尚未运行。之后,我允许代码运行或程序结束。当我使用 1 个或两个名为 test.csv 和 test2.csv 的测试文件运行程序时,我没有任何错误。一旦我添加随机名称 .csv 并尝试运行它们,我就会收到 import-csv 找不到文件的错误,并且路径告诉我文件不正确,它来自脚本的位置。

这是我的代码:

$fileDirectory = "c:\test";

$CheckRun = Get-Content c:\test\checkrun.txt
Write-Host $($CheckRun)

if($CheckRun -eq "notrunning") {

    Get-ChildItem $fileDirectory -Filter *.csv | Foreach-Object {
        $list= Import-Csv $_
        $State = "running"
        $basename = $_.BaseName
        $file = $FileDirectory + "\" + $basename + ".csv"
        $ArchiveFile = $fileDirectory + "\archive\" + $basename + "old.csv"
        foreach ($entry in $list) {
            # will run command here using the entries from the CSVs
            write-Host $($entry.EMAIL) $($entry.FIRSTNAME) $($entry.LASTNAME) $($entry.PASSWORD)
        }

        Move-Item $($file) ${ArchiveFile} -force

        Write-Host "Press any key to continue ..."

        $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        $State > c:\test\Checkrun.txt

    }

    $State = "notrunning"
    $State > c:\test\Checkrun.txt
    Write-Host "Press any key to continue ..."

    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
else {
    Write-Host "Press any key to continue ..."

    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit
}

【问题讨论】:

    标签: powershell csv powershell-2.0


    【解决方案1】:

    当您获得子项时,您将获得一个文件对象。尝试引用全名而不是它对我有用:

     Get-ChildItem $fileDirectory -Filter *.csv | Foreach-Object {
            $list= Import-Csv $_.fullname
    

    否则,它会尝试查看您正在为文件运行脚本的路径,而不是 C:\test\filename.csv

    【讨论】:

    • 这解决了我的问题,我可以说它想要引用我正在运行的文件路径,但我不知道正确的语法。我还注意到它部分起作用的原因是我在与脚本相同的文件夹中拥有前两个 CSV 的副本。谢谢,
    猜你喜欢
    • 2018-06-22
    • 2017-07-03
    • 1970-01-01
    • 2012-11-12
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多