I have some problem with this line of code. Currently I'm able to loop all the xml files name inside a folder. But the how to use that variable and put after C:\Windows\System32\Tasks\Job\? Currently the powershell always detect it as the text.
$fileDirectory = "C:\Windows\System32\Tasks\Job\*.xml";
foreach($file in Get-ChildItem $fileDirectory)
{
$file.name
Register-ScheduledTask -xml (Get-Content "C:\Windows\System32\Tasks\Job\$file.name" | Out-String) -TaskName $file.name -TaskPath "\Job" -User "MyAccount" –Force
}
You need to surround your $file.name
in "C:\Windows\System32\Tasks\Job\$file.name"
with the Subexpression Operator $()
, otherwise it's just trying to substitute the $file
part.
Compare this:
PS> $file = get-item "c:\temp\temp.txt"
PS> "C:\Windows\System32\Tasks\Job\$file.name"
C:\Windows\System32\Tasks\Job\C:\temp\temp.txt.name
with this:
PS> $file = get-item "c:\temp\temp.txt"
PS> "C:\Windows\System32\Tasks\Job\$($file.name)"
C:\Windows\System32\Tasks\Job\temp.txt
The first example evaluates $file
(which is a System.IO.FileInfo object) to C:\temp\temp.txt
and just replaces $file
in the string, leaving a trailing .name
as literal text.
The second example evaluates $($file.name)
to temp.txt
(which is a string) instead and replaces the entire $($file.name)
subexpression.
But simpler still, in your case you could just use $file.FullName
which gives the full path:
PS> $file = get-item "c:\temp\temp.txt"
PS> $file.FullName
c:\temp\temp.txt