Powershell ISE - 未解释变量

Powershell ISE - Variable not interpreted

我正在 Powershell ISE 中试验以下脚本,但是 returns 执行时出错。

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

读取主机部分工作正常,但是当它移动到 psexec 行时它 returns

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

您无需引用任何内容。如果需要,PowerShell 将自动引用。

psexec \$computerName cmd

为了扩展其他一些答案,一位同事向我展示了更复杂的 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 有帮助。