I face an issue when I run the following command
$x = "c:\Scripts\Log3.ps1"
$remoteMachineName = "172.16.61.51"
Invoke-Command -ComputerName $remoteMachineName -ScriptBlock {& $x}
The expression after '&' in a pipeline element produced an invalid object. It must result in a command name, script
block or CommandInfo object.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : BadExpression
+ PSComputerName : 172.16.61.51
Issue is not seen if I dont use $x variable
Invoke-Command -ComputerName $remoteMachineName -ScriptBlock {& 'c:\scripts\log3.ps1'}
Directory: C:\scripts
Mode LastWriteTime Length Name PSComputerName
---- ------------- ------ ---- --------------
-a--- 7/25/2013 9:45 PM 0 new_file2.txt 172.16.61.51
Variables in your PowerShell session are not transferred to sessions created with Invoke-Command
You need to use the -ArgumentList parameter to send the variables your command and then use the $args array to access them in the script block so your command will look like:
Invoke-Command -ComputerName $remoteMachineName -ScriptBlock {& $args[0]} -ArgumentList $x
If you work with variables inside a script block you need to add the modifier using:. Otherwise Powershell would search for the var definition inside the script block.
You can use it also with the splatting technique. E.g.:#using:params
Like this:
# C:\Temp\Nested.ps1
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String]$Msg
)
Write-Host ("Nested Message: {0}" -f $Msg)
# C:\Temp\Controller.ps1
$ScriptPath = "C:\Temp\Nested.ps1"
$params = #{
Msg = "Foobar"
}
$JobContent= {
& $using:ScriptPath #using:params
}
Invoke-Command -ScriptBlock $JobContent -ComputerName 'localhost'
Related
hi i' m trying to retrieve the vhdx of specified vmname from the remote host server
here part of the script
$pth="C:\path\resize-vm"
$list=gc $pth\list-host.txt
foreach ($hostserver in $list) {
$vm=(Invoke-Command -ComputerName $hostserver -ScriptBlock {Get-VM}).VMName
Write-Host -NoNewline " here the vm installed in " $hostserver `r`n $vm
$vmname=Read-Host -Prompt "please chose a vmname to resize "
#the issue in the last line
$pathvhd=Invoke-Command -ComputerName $hostserver -ScriptBlock {(Get-VMHardDiskDrive -VMName $vmname).path}
When I launch this command $vmname="dc-kozhan"
I am getting this error
Cannot validate argument on parameter 'VMName'. The argument is null
or empty. Provide an argument that is not null or empty, and then try
the command again.
+ CategoryInfo : InvalidData: (:) [Get-VMHardDiskDrive], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.HyperV.PowerShell.Commands.GetVMHardDiskDrive
Command
+ PSComputerName : h-uludag-3
But when I specified dc-kozhan literally it work
PS C:\Users> Invoke-Command -ComputerName $hostserver -ScriptBlock {(Get-VMHardDiskDrive -VMName "DC-KOZAHAN")
.path}
V:\DC-KOZAHAN\DC-KOZAHAN-SYSTEM.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-DIRECTORY.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-SYSVOL.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-BACKUP.vhdx
does anyone have an idea why it does not work when it's specified in a variable
You need to understand how to pass arguments inside the scriptblock. The scope is different when you try to pass the value inside the scriptblock. As a result, $VMname is becoming null in your first statement.
Kindly change your existing Invoke-command statement to the below one:
Invoke-Command -ComputerName $hostserver -ScriptBlock {Param([string]$vmname)(Get-VMHardDiskDrive -VMName $vmname)} -ArgumentList $vmname
Also, my suggestion for you to read about the argumentlist in powershell in case invoke-command
Hope it helps.
I have a script that works to run an executable and wait until done in PS but I need to modify it to use a path defined in a variable earlier in the script.
Working:
$job = Start-Job `
-InitializationScript { Set-Location C:\MyDirectory\ } `
-ScriptBlock { C:\MyDirectory\MyCmdLineExecutable.exe }
Wait-Job $job
Receive-Job $job
Not working:
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job `
-InitializationScript { Set-Location $Path } `
-ScriptBlock { $ExePath }
Wait-Job $job
Receive-Job $job
Here's the error:
Set-Location : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
At line:1 char:2
+ Set-Location $Path
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], PSArgumentNullException
+ FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
49 Job49 BackgroundJob Failed False localhost $ExePath
Running startup script threw an error: Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
Combining info from Start-Job docs with About_Scopes article, I am certain of that you need to use -InputObject parameter:
Specifies input to the command. Enter a variable that contains the
objects, or type a command or expression that generates the
objects. In the value of the ScriptBlock parameter, use the
$Input automatic variable to represent the input objects.
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job -InputObject #( $Path, $ExePath) `
-InitializationScript { <# $Input variable isn't defined here #> } `
-ScriptBlock {
$aux = $Input.GetEnumerator()
Set-Location $aux[0]
& $aux[1] }
Wait-Job $job
Receive-Job $job
BTW, to run commands that are stored in variables and represented by strings, use & Call operator. See the difference:
$ExePath ### output only
& $ExePath ### invocation
I think you want Start-Process with the -Wait parameter. You can also specify the -WorkingDirectory parameter to specify the working directory for the new process. Example:
Start-Process notepad -WorkingDirectory "C:\Program Files" -Wait
Write-Host "Finished"
When you run this script, Notepad will open but the script won't continue until it closes. When you close Notepad, the Write-Host line runs.
I am trying to follow this article to expand a variable in a scriptblock
My code tries this:
$exe = "setup.exe"
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock {cmd /c 'C:\share\[scriptblock]::Create($exe)'}
How to fix the error:
The filename, directory name, or volume label syntax is incorrect.
+ CategoryInfo : NotSpecified: (The filename, d...x is incorrect.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : remote_computer
You definitely don't need to create a new script block for this scenario, see Bruce's comment at the bottom of the linked article for some good reasons why you shouldn't.
Bruce mentions passing parameters to a script block and that works well in this scenario:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { param($exe) & "C:\share\$exe" } -ArgumentList $exe
In PowerShell V3, there is an even easier way to pass parameters via Invoke-Command:
$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { & "C:\share\$using:exe" }
Note that PowerShell runs exe files just fine, there's usually no reason to run cmd first.
To follow the article, you want to make sure to leverage PowerShell's ability to expand variables in a string and then use [ScriptBlock]::Create() which takes a string to create a new ScriptBlock. What you are currently attempting is to generate a ScriptBlock within a ScriptBlock, which isn't going to work. It should look a little more like this:
$exe = 'setup.exe'
# The below line should expand the variable as needed
[String]$cmd = "cmd /c 'C:\share\$exe'"
# The below line creates the script block to pass in Invoke-Command
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd)
Invoke-Command -ComputerName $j -Credential $credentials -ScriptBlock $sb
I want to call a VBScript located on a server with a PowerShell script, I want to pass parameters in the VBS by using invoke-command.
Code:
$username = [Environment]::UserName # Get the current user name
# Get with a Credential the logins to connect to an AS400 Server
$credential = $host.ui.PromptForCredential("Login", "Please enter your ID.", "", "")
$ASUser = $credential.Username.Substring(1)
$ASPwrd = $credential.GetNetworkCredential().password
# Call of the VBS on the server with these parameters
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs"
} -ArgumentList $username, $ASUser, $ASpwrd
But I've got an issue caused by the parameters in the VBS, at these lines:
User = WScript.Arguments(0)
UID = WScript.Arguments(1)
PWD = WScript.Arguments(2)
The PowerShell script returns me this error:
C:\MyScript.vbs(64, 1) Microsoft VBScript runtime error: Subscript out of range
+ CategoryInfo : NotSpecified: (C:\Excel Script...pt out of range:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The line 64 is User = WScript.Arguments(0).
It seems that my VBS does not recognize that I pass parameters, so I think the problem comes from the PS script, I also tried to pass the parameters like this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs" $username $ASUser $ASpwrd
}
It does not work.
You're passing arguments into the scriptblock, but you never use them.
Change this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs"
} -ArgumentList $username, $ASUser, $ASpwrd
into something like this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
CSCRIPT "C:\MyScript.vbs" $args[0] $args[1] $args[2]
} -ArgumentList $username, $ASUser, $ASpwrd
or this:
Invoke-Command -ComputerName MyServerName -ScriptBlock {
Param($user, $user2, $pass2)
CSCRIPT "C:\MyScript.vbs" $user $user2 $pass2
} -ArgumentList $username, $ASUser, $ASpwrd
I'm trying to get the Invoke-Command cmdlet working with a CredSsp session by passing a locally defined function.
I have two local functions:
MyCopy which just invokes Copy-Item cmdlet on passed params with additional switches
MyCopyReturn which is the same as above, but in addition has return statement at the end
Now when I pass those functions to Invoke-Command without -Session parameter, they both succeed.
However, when specifying -Session for Invoke-Command, MyCopy fails with following exception (2. case):
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
+ PSComputerName : localhost
Could someone please explain why result of passing MyCopyReturn is different from passing MyCopy?
function MyCopy ($from, $to) {
Copy-Item $from $to -Force -Recurse -Verbose
}
function MyCopyReturn ($from, $to) {
Copy-Item $from $to -Force -Recurse -Verbose
return
}
$credential = Get-Credential
$computerName = 'localhost'
$session = New-PSSession -ComputerName $computerName -Credential $credential -Authentication Credssp
# src is a file
$src = "c:\sandbox\a\test"
# dest is a directory
$dest = "c:\sandbox\b"
# 1.
# MyCopy works fine without giving session
Invoke-Command -ScriptBlock ${function:MyCopy} -ArgumentList $src,$dest
# 2.
# MyCopy DOESN'T WORK when session is given
Invoke-Command -Session $session -ScriptBlock ${function:MyCopy} -ArgumentList $src,$dest
# 4.
# MyCopyReturn works fine without the session
Invoke-Command -ScriptBlock ${function:MyCopyReturn} -ArgumentList $src,$dest
# 3.
# MyCopyReturn works fine with session too
Invoke-Command -Session $session -ScriptBlock ${function:MyCopyReturn} -ArgumentList $src,$dest
Remove-PSSession $session
I make some digging with ILSpy and can say, that the problem in the bug in ScriptBlock.GetPowerShell method. It does not bind parameters properly, if them come not from param block:
function f($Arg){write "`$Arg=`"$Arg`";`$Args=`"$Args`""}
function g{param($Arg) write "`$Arg=`"$Arg`";`$Args=`"$Args`""}
$Function:f.GetPowerShell('Test1','Test2').Invoke()
# $Arg="";$Args="Test1 Test2"
$Function:g.GetPowerShell('Test1','Test2').Invoke()
# $Arg="Test1";$Args="Test2"
As you can see, $Function:f.GetPowerShell('Test1','Test2') bind both arguments to $Args automatic variable and nothing get bound to $Arg. So when you invoke this command
Invoke-Command -Session $session -ScriptBlock ${function:MyCopy} -ArgumentList $src,$dest
$from and $to does not get bound properly and cause error.
Why error does not happens when you not use -Session parameter?
Looks like Invoke-Command have to convert ScriptBlock to PowerShell to invoke command in remote session and that does not required when ScriptBlock invoked locally.
Why MyCopyReturn does not cause same error?
Not all ScripBlocks can be converted to PowerShell by GetPowerShell method (in particular, it is required that ScriptBlock must have a single statement, having another statement return violate this). If that is the case (GetPowerShell throws ScriptBlockToPowerShellNotSupportedException), than Invoke-Command use some backup scenario to convert ScriptBlock to PowerShell and that scenario does not suffer from bug of GetPowerShell method.