如何使用 powershell 正确获取变量名并将其导入任务调度程序?

How to properly get the variable name and import it to task schedular with powershell?

我对这行代码有一些问题。目前,我能够在一个文件夹中循环所有 xml 文件名。但是如何使用该变量并将其放在 C:\Windows\System32\Tasks\Job\ 之后?目前 powershell 始终将其检测为文本。

$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
}

您需要用 Subexpression Operator $()"C:\Windows\System32\Tasks\Job$file.name" 中的 $file.name 包围起来,否则它只是试图替换 $file 部分。

比较这个:

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

有了这个:

PS> $file = get-item "c:\temp\temp.txt"
PS> "C:\Windows\System32\Tasks\Job$($file.name)"
C:\Windows\System32\Tasks\Job\temp.txt

第一个示例将 $file(这是一个 System.IO.FileInfo 对象)计算为 C:\temp\temp.txt 并仅替换字符串中的 $file,留下尾随 .name 作为文字文本。

第二个示例将 $($file.name) 计算为 temp.txt(这是一个字符串)并替换整个 $($file.name) 子表达式。

但更简单的是,在您的情况下,您可以使用 $file.FullName 来提供完整路径:

PS> $file = get-item "c:\temp\temp.txt"
PS> $file.FullName
c:\temp\temp.txt

另一种选择是使用 f 格式运算符。

$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
}