【问题标题】:Error assigning variable in scheduled task action在计划任务操作中分配变量时出错
【发布时间】:2018-10-22 15:52:09
【问题描述】:

我有一个 .xml 文件,其中包含用户名和加密密码(API 的 accessid 和密钥)。使用以下行,我检索凭据:

$Credential = Import-CliXml -Path "${env:\userprofile}\token.xml"

这在 shell 中效果很好,但我需要安排这个命令(以及使用 cred 的脚本)。在计划任务中,我正在启动 powershell.exe 并将以下内容作为参数传递:

-Command "& $credential = Import-CliXml -Path ${env:\userprofile}\token.Cred"

但我得到了错误:

& :无法识别术语“System.Management.Automation.PSCredential” 作为 cmdlet、函数、脚本文件或可运行程序的名称。查看 名称的拼写,或者如果包含路径,请验证路径 是正确的,然后再试一次。 在行:1 字符:3 + & System.Management.Automation.PSCredential = Import-CliXml -Path C:\ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (System.Manageme...on.PSCredential:String) [], CommandNotFoundException +fullyQualifiedErrorId:CommandNotFoundException

我尝试了几种变体,包括:

-Command (& $credential = Import-CliXml -Path ${env:\userprofile}\token.Cred)
-Command ($credential = Import-CliXml -Path ${env:\userprofile}\token.Cred)
-Command "$credential = Import-CliXml -Path ${env:\userprofile}\token.Cred"

但我得到了同样的错误。我需要该变量,因为我还将运行以下命令(在同一操作中):

.\script.ps1 -AccessId $Credential.UserName -AccessKey ((System.Runtime.InteropServices.Marshal::PtrToStringAuto(System.Runtime.InteropServices.Marshal::SecureStringToBSTR($Credential.Password))))

什么给了?

【问题讨论】:

    标签: powershell scheduled-tasks


    【解决方案1】:
    # using cmd.exe
    powershell.exe -Command "& {$credential = Import-CliXml -Path ${env:\userprofile}\token.Cred}"
    # using powershell, escape special characters
    Start-Process powershell.exe -ArgumentList "-Command `"& {`$credential = Import-CliXml -Path `${env:\userprofile}\token.Cred;pause}`""
    

    【讨论】:

    • = : The term '=' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:5 + & { = Import-CliXml -Path C:\Users\srvc_tools_app\token.Cred} + ~ + CategoryInfo : ObjectNotFound: (=:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 似乎不喜欢在脚本块内分配变量。
    • 您是从脚本调用它还是尝试从命令行(cmd.exe/powershell.exe)运行它?
    • 它将在计划任务中,但目前,我正在从 PS 会话运行它。
    猜你喜欢
    • 2014-03-18
    • 2020-06-01
    • 2010-11-13
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多