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
Another option is to use the f-format operator.
$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\{0}" -f $file.name | Out-String) -TaskName $file.name -TaskPath "\Job" -User "MyAccount" –Force
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.