powershell set-location无法正常工作

时间:2017-09-05 20:04:58

标签: python powershell

我正在尝试连接到远程Windows机器并使用powershell执行命令。

我编写了一个以下脚本,该脚本需要3个参数,我将在脚本中使用。

脚本块有set-location,它将设置位置,并在该位置使用命令启动可执行文件:installutil.exe <exe name>

这是脚本:

param(
    [string]$Hostname,
    [string]$Exe_Location,
    [string]$Exe_Filename  
)

Write-Host $MyInvocation.MyCommand.Path

$pso = New-PSSessionOption –NoMachineProfile

# user crtedentials
$Username = "XXXXXXXX"
$Password = "XXXXXXXX"

# To avoid Manual entry of Username and Password
$Secure_String = convertto-securestring $Password -asplaintext -force
$User_cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Secure_String

# Create Session
$sess = New-PSSession -ComputerName $Hostname -SessionOption $pso -credential $User_cred

#Run a powershell script in the session. Anything you put in ScriptBlock { }, will run remotely on the server.
Invoke-Command -Session $sess -ScriptBlock {Set-Location $Exe_Location;InstallUtil.exe $Exe_Filename}
Write-Host $MyInvocation.MyCommand.Path

# Remove session
Remove-PSSession $sess

执行命令:

.\<name>.ps1 -Hostname <hostname> -Exe_Location "C:\Program Files\ABC\BCD" -Exe_Filename "test_me.exe"

错误是:

Can not process argument because the value of argument "path" is null. Change the value of the argument "path" to non-null value.
+ CategoryInfo  :InvalidArgument: (:) [Set-Location], PSArgumentNullException

1 个答案:

答案 0 :(得分:0)

在远程计算机上创建$ Exe_Location和$ Exe_Filename。由于在远程机器上没有定义这些变量,因此它们是空的

Invoke-Command -Session $sess -ScriptBlock {Set-Location $Exe_Location;InstallUtil.exe $Exe_Filename}

使用-argumentlist传递变量

Invoke-Command -Session $sess -ScriptBlock {param($Exe_Location, $Exe_Filename) Set-Location $Exe_Location;InstallUtil.exe $Exe_Filename} -ArgumentList  $Exe_Location, $Exe_Filename