Foreach ($dir in @("C:","D:","E:","H:","I:"))
{
IF (Test-Path $dir\folder\Office_task.bat)
{
Copy-Item $dir\folder\Office_task.bat C:\Users -Force
break
}
IF (Test-Path $dir\folder\xml\Office.xml)
{
Register-ScheduledTask -Xml (Get-Content "$dir\folder\xml\Office.xml" | Out-String) -TaskName "Office" -Force
break
}
}
How to first loop through all drives and copy a file from the first it is found, and then loop through all drives again and register a task.
Currently my file is only being copied. May be because of an incorrect break
command.
答案 0 :(得分:1)
Resolve-Path
can help here:
The first two checks find the correct path, then if more then one path found it use the first one, then execute your task for that path
$Drives = @("C:","D:","E:","H:","I:")
$OfficePath = ($Drives | % {Resolve-Path $_\folder\Office_task.bat -EA SilentlyContinue}).Path
$XmlPath = ($Drives | % {Resolve-Path $_\folder\xml\Office.xml -EA SilentlyContinue}).Path
$OfficePath = $OfficePath | select -First 1
$XmlPath = $XmlPath | select -First 1
if ($OfficePath) {Copy-Item $OfficePath C:\Users -Force}
if ($XmlPath) {Register-ScheduledTask -Xml (Get-Content $XmlPath | Out-String) -TaskName "Office" -Force}