.net 如何避免;不能对空值表达式调用方法";文件可能为空时出错?
我想打开一个文件,替换一些内容,然后附加到另一个文件。我写了一个Powershell脚本:.net 如何避免;不能对空值表达式调用方法";文件可能为空时出错?,.net,powershell,.net,Powershell,我想打开一个文件,替换一些内容,然后附加到另一个文件。我写了一个Powershell脚本: (Get-Content file.txt).replace("abc", "def") | Add-Content other.txt 除非file.txt是空的,否则这可以正常工作。然后它给出了一个错误 不能对空值表达式调用方法 为什么会出现这样的错误?我怎样才能避免呢 我希望打开一个空文件时返回空文件,而不是像在unix中那样返回空文件 cat file.txt | sed -r s/abc/de
(Get-Content file.txt).replace("abc", "def") | Add-Content other.txt
除非file.txt是空的,否则这可以正常工作。然后它给出了一个错误
不能对空值表达式调用方法
为什么会出现这样的错误?我怎样才能避免呢
我希望打开一个空文件时返回空文件,而不是像在unix中那样返回空文件
cat file.txt | sed -r s/abc/def/g >> other.txt
试一试:
(Get-Content file.txt).replace("abc", "def") | Add-Content other.txt -erroraction SilentlyContinue
对于erroraction
的类型还有其他选项,因此只要使用tab completion来查看它们,如果SilentlyContinue不能满足您的要求,就可以对它们进行测试
编辑:如果你需要知道某个东西失败是因为它是空的,请查看Bernard的答案。否则,这一行程序也应该工作,这取决于您的需求
$path = "\test.txt"
$path2 = "\test2.txt"
try{
$content = (Get-Content $path).replace("abc", "def") | Add-Content $path2
Write-Host "Successfully added content" -ForegroundColor Green
}catch{
if(!$content){
Write-Host "$path is empty" -ForegroundColor Yellow
}else{
throw $_
}
}
我认为在运行cmdlet时,您应该始终使用try/catch
希望这有助于使用PowerShell的
-Replace
操作符,而不是返回的字符串的Replace
方法(对于空文件为null)
(Get-Content file.txt) -Replace "abc", "def" | Add-Content other.txt