PowerShell预打印待移动文件时Out-File参数验证错误求助
问题排查:PowerShell Out-File 参数验证错误
问题描述
编写的PowerShell脚本原本用于将文件移动至归档文件夹,注释移动命令后希望先打印待移动文件信息,添加代码后执行出现以下错误:
Out-File : 无法验证参数“Encoding”的参数。参数“Logs\Archive\OutputOffAllFiles-log.txt”不属于ValidateSet属性指定的集合“unknown,string,unicode,bigendianunicode,utf8,utf7,utf32,ascii,default,oem”。请提供集合中的参数并重试。
At N:\Script\movefileprint.ps1:11 char:68
- ... | Out-File N:\Posting Logs\Archive\OutputOffAllFiles-log.txt -Append
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException
- FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.OutFileCommand
原完整脚本:
$source = "N:\Posting Logs" $dest = "N:\Posting Logs\Archive" # Create the Archive folder if it doesn't exist if (-not (Test-Path $dest)) { New-Item -ItemType Directory -Path $dest } #Get-ChildItem $source -File -Recurse | Move-Item -Destination {Join-Path $dest $_.Name} -Force #Get-ChildItem $source -File -Recurse |Out-File N:\Posting Logs\Archive\OutputOffAllFiles-log.txt -Append $_.FullName +$(Get-Date -Format yyyy-MM-dd) | Out-File N:\Posting Logs\Archive\OutputOffAllFiles-log.txt -Append
错误原因分析
$_变量无有效上下文:单独执行$_.FullName时,$_没有绑定任何管道输入对象(原脚本注释了Get-ChildItem的管道),导致该值为空,同时后续路径解析逻辑混乱。- 路径未加引号导致参数解析错误:输出路径
N:\Posting Logs\Archive\OutputOffAllFiles-log.txt包含空格,PowerShell会将空格后的Logs\Archive\OutputOffAllFiles-log.txt误认为是Out-File的-Encoding参数值,而该值不在Encoding的合法取值集合中,触发参数验证错误。
修复后的脚本
$source = "N:\Posting Logs" $dest = "N:\Posting Logs\Archive" # 创建归档文件夹(如果不存在) if (-not (Test-Path $dest)) { New-Item -ItemType Directory -Path $dest } # 遍历所有待归档文件,输出文件完整路径及当前日期到日志 Get-ChildItem $source -File -Recurse | ForEach-Object { "$($_.FullName) $(Get-Date -Format yyyy-MM-dd)" | Out-File "N:\Posting Logs\Archive\OutputOffAllFiles-log.txt" -Append }
修复说明
- 恢复
Get-ChildItem管道,通过ForEach-Object遍历每个文件,此时$_代表当前处理的文件对象,$_.FullName可正确获取文件完整路径。 - 给
Out-File的路径参数添加双引号,避免空格导致PowerShell错误解析参数。 - 使用字符串插值语法拼接文件路径和日期,比
+运算符更直观,可读性更强。
内容的提问来源于stack exchange,提问作者ptolearn
相关产品推荐
相关产品推荐

