使用-NoMachineProfile的Powershell invoke-command如何获取传递的args

时间:2012-07-16 18:39:19

标签: powershell invoke-command

问题

有没有人知道获取与$ MyInvocation相同数据的方法?强烈的偏好是仅使用内置的东西,而不是第三方添加软件来实现这一目标。

问题

使用-NoMachineProfile创建会话时,不会填充$ MyInvocation。我希望有一些其他方式来获取信息,就像[System.Environment] :: Username是$ env:USERNAME一样。

我无法改变调用方式。请不要建议删除-NoMachineProfile作为解决方案,因为这不是一个选项。

我不想依赖$ args,因为那是后期处理。即引号,变量和其他传递的参数不再与它们传递时的相同。

背景

$ MyInvocation.line包含提供0解析的确切命令。

e.g。 SomeScript.ps1

write-host ("Invoked line: "+$MyInvocation.line)

。\ somescript.ps1 foo bar“foo and bar” 产生以下输出

Invoked line: .\somescript.ps1 foo bar "foo and bar"

引号和所有,这意味着它能够被剪切和粘贴,并且完全以0用户翻译的方式运行。

-NoMachineProfile调用

$SE_ADMIN_CREDENTIALS = Get-Credential
$PS_SESSION_OPTIONS = New-PSSessionOption -NoMachineProfile
$arrayRemoteTarget = "thehostname"
$strScriptToRun = ".\somescript.ps1"
$StrArguments = "arg1,arg2,arg3"

$icmCommand = "Invoke-Command -Credential `$SE_ADMIN_CREDENTIALS -SessionOption `$PS_SESSION_OPTIONS -ComputerName `$arrayRemoteTarget -FilePath `$strScriptToRun -ArgumentList (`$strArguments).Split("","")"

Invoke-Expression $icmCommand

1 个答案:

答案 0 :(得分:0)

-sessionoption (new-pssessionoption -nomachineprofile)

是另一种方式。

我相信关于传递论点

$using:variable

是您要寻找的

例如

$listing = "*"
invoke-command -computername $computer -scriptblock {cd /; ls $using:listing}

我希望这是有道理的。

否则,您可以在文件中使用“ arg [0]”或“ args [0]”来运行脚本...应该可以工作...

最后一个注释,即您用引号引起来的引号,可能会弄乱您的脚本,我只是将split("","")替换为split(',')