Windows10 64位下PowerShell脚本Out-File找不到文件的求助
PowerShell脚本错误排查与修复
你的脚本存在多处语法、拼写问题,这些问题直接导致了执行异常,以下是具体问题和修复方案:
1. 未闭合的字符串语法错误
第3行代码未闭合双引号,导致后续逻辑混乱:
# 错误写法 write-host "Location is: -nonewline; # 修复后 write-host "Location is: " -nonewline;
2. 程序集名称拼写错误
第6行的数据库程序集名称少写了字母l,无法正确加载:
# 错误写法 [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Data.SqClient"); # 修复后 [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Data.SqlClient");
3. 变量引用错误(字符混淆)
第13行存在变量名混淆和符号错误:大写字母I和小写字母l混用,变量引用符号$写成了S:
# 错误写法 write-host "outputfiIe is: SoutputFiIe"; # 修复后 write-host "outputFile is: $outputFile";
4. 字符串引号不匹配
最后一行的字符串开头用双引号、结尾用单引号,导致语法中断:
# 错误写法 write-host "After WRITING INFORMATION TO FILE'; # 修复后 write-host "After WRITING INFORMATION TO FILE";
5. 文件名多余空格
第11行的文件名后缀前多了一个空格,会生成带空格的文件名(如civ_20230224_105513 .txt),与错误提示中的文件名不符,建议移除空格:
# 错误写法 [string] $fileName = "civ_" + (get-date).ToString("yyyyMMdd_HHmmss") + " .txt"; # 修复后 [string] $fileName = "civ_" + (get-date).ToString("yyyyMMdd_HHmmss") + ".txt";
额外优化:确保目标目录存在
如果C:\temp目录不存在,Out-File会直接报错,可在写入文件前添加目录检查逻辑:
if (-not (Test-Path "C:\temp")) { New-Item -ItemType Directory -Path "C:\temp" | Out-Null }
修复后的完整脚本示例
Try{ $Error.Clear(); write-host "After Clear Error"; write-host "Location is: " -nonewline; (get-location).Path [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"); [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Data.SqlClient"); [void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO"); Write-host "After setting systems for forms"; [string] $CRLF = "`r`n" [string] $fileName = "civ_" + (get-date).ToString("yyyyMMdd_HHmmss") + ".txt"; Write-host "File Name is: $fileName"; [string] $outputFile = ("C:\temp\" + $fileName); write-host "outputFile is: $outputFile"; [string] $newLocation = "G:\Teams\Data\support\"; Write-host "After setting FILE information"; # 确保输出目录存在 if (-not (Test-Path "C:\temp")) { New-Item -ItemType Directory -Path "C:\temp" | Out-Null } ($CRLF + "Script Run Commencing at " + (get-date).ToString("yyyyMMdd_HH:mm:ss.fff")) | out-file $outputFile -append -encoding ASCII; write-host "After WRITING INFORMATION TO FILE"; } Catch { Write-Error "脚本执行出错: $_" }
内容的提问来源于stack exchange,提问作者JamesNEW
相关产品推荐
相关产品推荐

