1

I am working on a script to automate adding users. I want to read from all CSV files in a directory until they are done and then I want to move those csvs to an archive. In the program I am checking a txt file to make sure another instance of the program is not already running. after that I am allowing the code to run or the program to end. When I run the program with 1 or two test files named test.csv and test2.csv I am not having any errors. Once I add random names .csv and try to run these through I am getting the error that import-csv cannot find the file and the path is is telling me the file at it no correct, its from the location of the script.

Here is my code:

$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
}

1 Answer 1

1

When you get the child items you are getting a file object. Try referenceing the fullname instead it workd for me:

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

Otherwise it is trying to look in the path that you are running the script for the file instead of C:\test\filename.csv

Sign up to request clarification or add additional context in comments.

1 Comment

That solved my problem, I could tell it was wanting to reference the file path I was running from, but I did not know the proper syntax. I also noticed the reason It worked partially is I had a copy of the first two CSVs in the same folder as the script. Thanks,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.