powershell - 在计划任务操作中分配变量时出错
问题描述
我有一个 .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))))
是什么赋予了?
解决方案
# 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}`""
推荐阅读
- r - 将堆积条形图从 R 转换为 ggplot2
- ssl - WebLogic(使用 SSL)作为任何 WSGI Web 服务器的代理
- java - java如何知道调用哪个方法?
- stripe-payments - Stripe 创建令牌适用于无效的 cvv
- javascript - VUE 无法访问属性,vm._events 未定义
- jquery - 添加按钮未通过 wapper append 调用颜色选择器
- python - pySpark withColumn 有两个条件
- ios - 减少 SwiftUI 部分之间的表单间距
- javascript - 将 JavaScript 变量设置为相对图像文件
- android - 向加载图像添加进度条