【问题标题】:Powershell ISE - Variable not interpretedPowershell ISE - 未解释变量
【发布时间】:2015-05-06 03:44:42
【问题描述】:

我正在 Powershell ISE 中试验以下脚本,但执行时会返回错误。

$computerName = Read-Host "Enter name of remote computer"
psexec \\"$computerName" cmd

Read-Host 部分工作正常,但是当它移动到 psexec 行时,它会返回

Enter name of remote computer: Computer

psexec : 
At line:2 char:1
+ psexec \\"$computerName" cmd
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com

所以脚本似乎没有传递 $computer 的值。我尝试了各种 " ' 组合都无济于事。

任何帮助将不胜感激,我在 powershell 脚本方面相当新手。

【问题讨论】:

  • 尝试将 \\ 放在引号 "\\$computerName" 中
  • 这次使用 psexec 失败:在 line:2 char:1 + psexec "\\$computerName" cmd 这次
  • 我不明白的部分是,如果我将 psexec 行替换为 Write-Host $ComputerName,它可以正常工作,将 $Computername 替换为在 Read-Host 语句期间键入的内容。
  • 我认为问题在于 ISE 使用 psexec。它在常规提示中对我来说很好。 ISE 的行为异常已不是第一次了。
  • 谢谢,我想你可能正在做一些事情,当从常规提示符运行时它工作正常

标签: powershell psexec powershell-ise


【解决方案1】:

为了扩展其他一些答案,一位同事向我展示了一种用于更复杂 psexec 字符串的方法如下:

#Use Psexec to Allow all remote connections and Enable PSRemoting
$psexec = "psexec -accepteula \\"+$targetIP+" -u "+$localadmin+" -p "+'"'+$str+'"'+' -h powershell.exe "&{"Set-Item wsman:localhost\client\trustedhosts -Value * -Force" ; "Enable-PSRemoting -SkipNetworkProfileCheck -Force"}"'
invoke-command -ScriptBlock {cmd /c $args[0]} -Argumentlist $psexec

虽然上面的代码实际上是在远程机器上调用 psexec 然后传递两个 powershell 命令,但身份验证问题导致 PS 中出现各种疯狂的错误。

希望这对某人或 OP 有所帮助。

【讨论】:

    【解决方案2】:

    更新:

    对,我试过了,好像行得通:

    $computerName = Read-Host "Enter Name of computer"
    $cred = Get-Credential
    psexec \\$computerName -u $cred.UserName -p $cred.GetNetworkCredential().Password ipconfig 2> $null #hide errors
    

    【讨论】:

    • 执行失败并使用 psexec : At line:2 char:1 + psexec \("$computerName") cmd
    • 试了几次就改了
    • 谢谢,试过了,同样的问题,无法连接到$Computername中指定的目标计算机
    • 我打开了我的虚拟机,添加用户名和密码后它就可以工作了 - 更新了答案
    • 如果你使用 CMD 它看起来像挂起,但它基本上是一个等待输入的 shell,但没有反馈给 powershell 主机。按ctrl+c,你就得到了你的powershell shell。您需要交互式外壳吗?
    【解决方案3】:

    你不需要引用任何东西。如果需要,PowerShell 会自动引用。

    psexec \\$computerName cmd
    

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2023-01-31
      • 2019-11-23
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多