我正在制作一个自动添加用户的脚本。我想读取目录中的所有CSV文件,直到它们完成,然后我想将这些csvs移动到存档。在程序中,我正在检查一个txt文件,以确保该程序的另一个实例尚未运行。之后,我允许代码运行或程序结束。当我用一个或两个名为test.csv和test2.csv的测试文件运行程序时,我没有任何错误。一旦我添加随机名称.csv并尝试运行这些通过我收到导入-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
}
答案 0 :(得分:1)
当您获得子项时,您将获得一个文件对象。尝试引用全名而不是它适用于我:
Get-ChildItem $fileDirectory -Filter *.csv | Foreach-Object {
$list= Import-Csv $_.fullname
否则它会尝试查看您运行该文件脚本的路径,而不是C:\ test \ filename.csv