Foreach 循环每天使用 Windows 任务运行计划,将文件导出到具有不同名称的 excel



我正在从租户服务器中提取消息并将它们导出到 excel 中,这对我来说效果很好。由于我不想每天手动运行脚本,因此我使用 windows task 来安排作业,这对我来说也很好用。但是每当任务每天早上运行时,它都会覆盖之前创建的文件,这并不好,因为我想让它创建一个具有不同名称的新文件,或者至少在它前面放一个数字来描述不同的文件。 我的 if 语句的测试路径运行良好,可以检查文件是否存在,但我的 foreach 循环不存在。我希望在使用不同名称运行脚本时创建一个新文件。我尝试使用 new-item 创建一个新文件,但我不想对路径进行硬编码,因为,我的 if 语句只会告诉我文件再次存在。请帮助我。

$User = "ABC"
$PWord = cat Z:mysecurestring.txt | convertto-securestring`
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
$session = New-SCSession -Credential $credential -Locale en-US
if(Test-Path Z:ScheduleMessageCenter.xlsx)
`{[system.windows.messagebox]::show('file already exist')}
Else{
foreach($ph in $GetMessageOut){$ph+1}`$GetMessageOut = Get-SCEvent -SCSession $session -EventTypes message | Select-Object ActionType,Id,AffectedTenantCount,ExternalLink,StartTime,`enter code here`
Title,EventTYpe,Category,LastUpdatedTime,UrgencyLevel,Endtime,Status,ActionRequiredByDate -ExpandProperty Messages | Export-Excel Z:ScheduleMessages.xlsx -AutoFilter
}

您可以使用此在文件名后添加日期和时间

Z:ScheduleMessages$((get-date).tostring("MMddyyyyHHmmss").xlsx

最新更新