你好,我写的脚本遇到了一个问题。在网上搜也没找到解决方法。
一个文件夹每天会收到一批固定的文件(至少理论上如此),大约保留 3 周。我要的文件内容像 csv,名字里总有两个字符串。“SDD_492813_030_031_IBZXCD” 和 “.csv”(实际扩展名是 .sav,而不是 .csv)。
脚本每天选出前一天的文件,导入后处理,不过三天前文件没来,脚本就失败了。我想先检查文件是否存在,没有就显示错误。
网上有人提到 [System.IO.File]::Exists($path) 或 test-path,可是除了这 2 个共同字符串,文件名每天都会变,无法预测,所以没法提前知道完整路径。
目前的代码是这样
$InputDirectory = "D:\Incoming"
$DailyInput = (Get-ChildItem -Path $InputDirectory -Include "*SDD_492813_030_031_IBZXCD*" "*.csv*" -Recurse | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-2) #pick files from the prior day
})
$Records = Import-Csv -Path $DailyInput -Delimiter '|' -ErrorAction Stop # read the selected file
我设想做个类似 if $DailyInput is null 的判断
{
显示错误
}
Else
{
$Records = Import-CSV …
}
先谢谢了
Tavin
从英语翻译·查看原文Hello, I've run into a difficulty with a script of mine. Searching the web hasn't turned up a solution.
A folder receives a particular set of files daily (at least in theory), retaining about 3 weeks of them. My target file has csv-like contents, and its name always includes these two strings. “SDD_492813_030_031_IBZXCD” and “.csv” (its actual extension is .sav, rather than .csv).
My script picks the previous day's file each day and imports it to process it, but three days ago the missing file caused it to fail. I'd like to test for the file's presence and show an error if it's absent.
Online sources mentionusing [System.IO.File]::Exists($path) or test-path, yet aside from the 2 shared strings, the name varies unpredictably each day, so I can't determine it's full path beforehand.
This is my current code
$InputDirectory = "D:\Incoming"
$DailyInput = (Get-ChildItem -Path $InputDirectory -Include "*SDD_492813_030_031_IBZXCD*" "*.csv*" -Recurse | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-2) #pick files from the prior day
})
$Records = Import-Csv -Path $DailyInput -Delimiter '|' -ErrorAction Stop # read the selected file
I'm imagining a test like if $DailyInput is null
{
Display an error
}
Else
{
$Records = Import-CSV …
}
Thanks beforehand
Tavin