How to run a command correct for CMD in remote box using PowerShell? -
i need run remote command of powershell cmd. command call cmd:
powershell -command "$encpass=convertto-securestring -asplaintext mypass -force;$cred = new-object system.management.automation.pscredential -argumentlist myuser,$encpass; invoke-command -computername "remote_computer_name" -scriptblock {<command>} -credential $cred;"
in place of <command>
(including < , > signs) can command can run in cmd.exe. example there can perl -e "print $^o;"
or echo "hello world!"
(note: there cannot perl -e 'print $^o;'
, because incorrect command cmd due single quotes). appears command perl -e "print $^o;"
, other command contains double quotes doesn't handled expected. here expect return os name of remote box perl's point of view, prints nothing due obscure handling of double quotes powershell and/or cmd.
so question following, how run command correct cmd in remote box using powershell?
there several possible problems command line in op. if command line in op being executed powershell $encpass , $cred substituted before (sub-instance) of powershell invoked. need use single quotes or else escape $ signs, example:
powershell -command "`$encpass=2" powershell -command '$encpass=2'
if, instead of using powershell, command line executed cmd, ^ has escaped, because cmd escape character.
and quoting " idea well. in few tests did had use unbalanced quotes command work, example, powershell:
powershell -command "`$encpass=`"`"a`"`"`"; write-host `$encpass"
worked, balanced quotes didn't.
to avoid this, robust way given in powershell command line help: powershell -?
:
# use -encodedcommand parameter: $command = 'dir "c:\program files" ' $bytes = [system.text.encoding]::unicode.getbytes($command) $encodedcommand = [convert]::tobase64string($bytes) powershell.exe -encodedcommand $encodedcommand
however there new feature in ps 3.0 supposed help, don't think robust. described here: http://blogs.msdn.com/b/powershell/archive/2012/06/14/new-v3-language-features.aspx, near middle of blog.
Comments
Post a Comment