首页 > 解决方案 > 在计划任务操作中分配变量时出错

问题描述

我有一个 .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))))

是什么赋予了?

标签: powershellscheduled-tasks

解决方案


# 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}`""

推荐阅读