简体   繁体   English

如何正确获取变量名并使用powershell将其导入到任务计划中?

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

I have some problem with this line of code.我对这行代码有一些问题。 Currently I'm able to loop all the xml files name inside a folder.目前我可以在文件夹中循环所有 xml 文件名。 But the how to use that variable and put after C:\\Windows\\System32\\Tasks\\Job\\?但是如何使用该变量并将其放在 C:\\Windows\\System32\\Tasks\\Job\\ 之后? Currently the powershell always detect it as the text.目前,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
}

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.您需要环绕你$file.name"C:\\Windows\\System32\\Tasks\\Job\\$file.name"子表达式运算符$()否则它只是试图替代$file的一部分。

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.第一个示例将$file (它是System.IO.FileInfo对象)计算为C:\\temp\\temp.txt并仅替换字符串中的$file ,将尾随的.name作为文字文本。

The second example evaluates $($file.name) to temp.txt (which is a string) instead and replaces the entire $($file.name) subexpression.第二个示例将$($file.name)temp.txt (这是一个字符串),并替换整个$($file.name)子表达式。

But simpler still, in your case you could just use $file.FullName which gives the full path:但更简单的是,在您的情况下,您可以使用$file.FullName提供完整路径:

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

Another option is to use the f-format operator.另一种选择是使用 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM