【问题标题】:Passing Powershell variables to batch files [duplicate]将Powershell变量传递给批处理文件[重复]
【发布时间】:2019-04-23 22:01:35
【问题描述】:

我在将 PowerShell 变量传递给 Invoke-Command(运行 CMD /C)时遇到了一些问题。问题是,$script_location 参数为空。

我的脚本在具有唯一名称 (20190423T1152100840Z.bat) 的 UNC 路径上创建了一个批处理文件,其中包含一些命令。最后,我想在服务器上运行这个生成的批处理文件。

$datum = Get-Date -Format FileDateTimeUniversal
$script_location = "\\uncpath\batchfile_$datum.bat"
$Username = 'user'
$Password = 'pass'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Add-Content $script_location " preferences_manager -u=user -p=pass -target=$env:username"
Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Invoke-Expression -Command:"cmd /c $script_location"
}

预期结果应该是Invoke-Command 运行$script_location 批处理文件。 目前的结果是$script_location 变量为空。

关于如何做到这一点的任何线索?

【问题讨论】:

标签: powershell batch-file


【解决方案1】:

将变量传递给 ScriptBlock 的最简单方法是在其名称前加上 using: 范围。

Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Invoke-Expression -Command:"cmd /c $using:script_location"
}

您也可以将其作为参数传递:

Invoke-Command -ComputerName "SERVERNAME" -Credential $cred -ScriptBlock {
    Param($ScriptLocation)
    Invoke-Expression -Command:"cmd /c $ScriptLocation"
} -ArgumentList $script_location

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多