我有功能齐全的poweshell脚本,但是当我尝试从MS Excel 2010运行它时,我收到一条错误消息"你无法在空值表达式上调用方法"和"无法索引到空数组"。 我不知道问题出在哪里,因为正如我所提到的,当我不尝试从Excel执行时,脚本可以正常运行。
感谢您提出任何建议。
$paths = Get-ChildItem 'E:\TEMP' -Filter '*.txt'
$delete = Get-Content 'E:\TEMP\TEMP1\delete.log'
ForEach ($path in $paths) {
$pathtmp = "$path.tmp"
$sr = New-Object -TypeName System.IO.StreamReader -ArgumentList $path
$sw = New-Object -TypeName System.IO.StreamWriter -ArgumentList $pathtmp
Do {
$line = $sr.ReadLine()
$Column = $line.split(",")
If ($delete -notcontains $Column[1]) {
$sw.WriteLine($line)
}
} Until ( $sr.EndOfStream )
$sr.close()
$sw.close()
Remove-Item $path
Rename-Item $pathtmp $path
}
如果文本文件的第一列与delete.log文件中的字符串匹配,则此脚本将从目录中的所有文本文件中删除整行。
答案 0 :(得分:0)
脚本的一个问题是,它通常只有在脚本放置的目录内运行时才会执行,我认为。
在这种情况下,它将是e:\ temp \ temp1。
这可能是excel抱怨的原因,因为工作目录已经被设置到除脚本之外的其他地方
如果稍微修改它,可以使它在任何地方工作
其中一种可能的解决方案可能是为读取和写入文件变量分配完整的工作路径
尝试使用这些脚本:
test.ps1脚本(在e:\ temp \ temp1中)
$paths = Get-ChildItem 'e:\TEMP' -Filter '*.txt'
$delete = Get-Content 'e:\TEMP\TEMP1\delete.log'
ForEach ($path in $paths) {
$fpath = $path.fullname
$pathtmp = "$fpath.txt"
$sr = New-Object -TypeName System.IO.StreamReader -ArgumentList "$fpath"
$sw = New-Object -TypeName System.IO.StreamWriter -ArgumentList "$pathtmp"
Do {
$line = $sr.ReadLine()
$Column = $line.split(",")
If ($delete -notcontains $Column[0]) {
$sw.WriteLine($line)
}
} Until ( $sr.EndOfStream )
$sr.close()
$sw.close()
Remove-Item "$fpath"
Rename-Item "$pathtmp" "$fpath"
}
excel宏
Sub test()
Call Shell(Environ$("COMSPEC") & " /c powershell -file E:\temp\temp1\test.ps1", vbNormalFocus)
End Sub