PowerShell - 抱歉,我们找不到 Microsoft.PowerShell.Core\FileSystem::



我正在尝试修改由Boe Prox创建的脚本,该脚本将多个CSV文件组合到一个Excel工作簿上以在网络共享上运行。

当我在本地运行时,脚本执行得很好,并将多个.csv文件合并到一个Excel工作簿中。

Clear-Host
$OutputFile = "ePortalMonthlyReport.xlsx"
$ChildDir = "C:MonthlyReport*.csv"
cd "C:MonthlyReport"
echo "Combining .csv files into Excel workbook"
. C:PowerShellConvertCSVtoExcel.ps1
Get-ChildItem $ChildDir | ConvertCSVtoExcel -output $OutputFile
echo " "

但是当我修改它以从网络共享中运行时,进行以下更改:

Clear-Host
# Variables
$OutputFile = "ePortalMonthlyReport.xlsx"
$NetworkDir = "\sqltest2dev_ePortalMonthly_Report"
$ChildDir = "\sqltest2dev_ePortalMonthly_Report*.csv"
cd "\sqltest2dev_ePortalMonthly_Report"
echo "Combining .csv files into Excel workbook"
. $NetworkDirConvertCSVtoExcel.ps1
Get-ChildItem $ChildDir | ConvertCSVtoExcel -output $OutputFile
echo " "

我得到一个错误,它看起来像使用网络路径两次,我不知道为什么:

将。csv文件合并到Excel工作簿

转换 sqltest2 dev_ePortal _statsbycounty.csv Monthly_Report 001命名工作表001_StatsByCounty——做

打开csv Microsoft.PowerShell.CoreFileSystem::sqltest2dev_ePortalMonthly_Report\sqltest2dev_ePortalMonthly_Report 001_statsbycountry .csv) in excel in temp workbook

对不起,我们找不到Microsoft.PowerShell.CoreFileSystem::sqltest2dev_ePortalMonthly_Report\sqltest2dev_ePortalMonthly_Report01_StatsByCounty.csv。它是否可能被移动、重命名或删除?

谁对解决这个问题有什么想法?

谢谢,

因为在脚本中它使用以下正则表达式:

[regex]$regex = "^w:\"

匹配以驱动字开头的路径,例如c:datafile.csv匹配而datafile.csv不匹配。它使用这个是因为(显然)Excel需要一个完整的路径,所以如果文件路径不匹配,它会将当前目录添加到它的前面:

#Open the CSV file in Excel, must be converted into complete path if no already done
    If ($regex.ismatch($input)) {
        $tempcsv = $excel.Workbooks.Open($input) 
        }
    ElseIf ($regex.ismatch("$($input.fullname)")) {
        $tempcsv = $excel.Workbooks.Open("$($input.fullname)") 
        }    
    Else {    
        $tempcsv = $excel.Workbooks.Open("$($pwd)$input")      
        }

您的文件路径将是\serversharedatafile.csv,并且它没有看到驱动器号,因此它点击最后一个选项并将$pwd(当前工作目录的一个自动变量)插入到文件路径的开头。

如果你编辑他的脚本并将正则表达式更改为:

,你可能会逃脱
[regex]$regex = "^w:\|^\\"

,它将匹配以\开头的路径,并且可以在不更改它的情况下使用。

或者编辑最后一个选项(~第111行),也写...Open("$($input.fullname)"),就像第二个选项一样

几乎在脚本调用$pwd而不是$PSScriptRoot的每个实例中都会引起许多问题。用快速查找和替换替换所有实例

$pwd看起来像:

PS Microsoft.PowerShell.CoreFileSystem::\foobar

$PSScriptRoot看起来像:

\foobar

我为自己修复的第二部分是@TessellatingHeckler指出的。我采取了更长远的方法。

这不是最有效的方法……但对我来说很清楚。
[regex]$regex = "^w:\"
[regex]$regex2 = "^\\"
$test = 0
If ($regex.ismatch($input) -and $test -eq 0 ) {
$tempcsv = $excel.Workbooks.Open($input)
$test = 1 }
If ($regex.ismatch("$($input.fullname)") -and $test -eq 0) {
$tempcsv = $excel.Workbooks.Open("$($input.fullname)") 
$test = 1}
If ($regex2.ismatch($input) -and $test -eq 0) {
$tempcsv = $excel.Workbooks.Open($input)
$test = 1 }
If ($regex2.ismatch("$($input.fullname)") -and $test -eq 0) {
$tempcsv = $excel.Workbooks.Open("$($input.fullname)")
$test = 1}
If ($test -eq 0) {    
$tempcsv = $excel.Workbooks.Open("$($PSScriptRoot)$input") 
$test = 0 }

最新更新