Powershell passing variables to remote script - powershell

I have the following cmd file:-
PowerShell.exe -noexit E:\wwwroot\domains\processes\AddDirectory.ps1 -Param testdomain.co.uk
which goes through to:-
$Session = New-PSSession -ComputerName 192.168.0.25
$script = {
Param($Param1)
set-executionpolicy unrestricted -force
# Set Variables
$domain = $Param1
$sitepath = "e:\domains\" + $domain
# Check for physical path
if (-not (Test-Path -path $sitePath))
{
New-Item -Path $sitepath -type directory
New-Item -Path $sitepath\wwwroot -type directory
}
set-executionpolicy restricted -force
}
Invoke-Command -Session $Session -ScriptBlock $script
But it just runs but does nothing.
If I declare the $domain variable as $domain = 'testdomain.co.uk' it works but it doesn't want to pass through the var from the cmd file. What am I doing wrong? I've tried to put it in the Invoke-Command as -ArgumentsList -$Param1 but that doesn't work either.....
Any ideas greatfully received
Thanks
Paul
Update - I've updated my code as per below but getting same issue:-
param($domainName)
$script = {
Param($Param1)
set-executionpolicy unrestricted -force
# Set Variables
$domain = $Param1
$sitepath = "e:\domains\" + $domain
# Check for physical path
if (-not (Test-Path -path $sitePath))
{
New-Item -Path $sitepath -type directory
New-Item -Path $sitepath\wwwroot -type directory
New-Item -Path $sitepath\db -type directory
New-Item -Path $sitepath\stats -type directory
}
set-executionpolicy restricted -force
}
$Session = New-PSSession -ComputerName 192.168.0.25
Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName

You need to use a param block in the script, the argument you pass to the file will be assign to $domainName and you will use it to pass the value to the scriptblock :
PowerShell.exe -noexit E:\wwwroot\domains\processes\AddDirectory.ps1 testdomain.co.uk
# script file
param($domainName)
$script = {
Param($Param1)
...
$domain = $Param1
...
}
$Session = New-PSSession -ComputerName 192.168.0.25
Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName

Related

PowerShell cannot use New-PSSessions right after Invoke-CimMethod (The runspace state is not valid for this operation)

The two code below works independently, however, they cannot work in the same script. I really need help, there's got to be something incompatible.
The first part of my script uses Invoke-CimMethod to Enable-PSRemoting, and it works.
Variables
$hostname = 'PC1'
$Session = New-PSSession $hostname
$DestinationPath = "C:\windows\temp"
Part 1
$SessionArgs = #{
ComputerName = $hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = #{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession #SessionArgs
Arguments = #{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod #MethodArgs
The second part of my code works if the first part above is not present. It is to create a TEMP folder, and then copy an entire folder into TEMP.
Part 2
Invoke-Command -Session $Session -ScriptBlock { Param($Destination) New-Item -Path $Destination -ItemType Directory -ErrorAction SilentlyContinue} -ArgumentList $DestinationPath
Copy-Item -Path "\\shared\folder\foo\bar" -ToSession $Session -Destination "C:\windows\temp\" -recurse -force
Error
Copy-Item : The runspace state is not valid for this operation.
What's weird is I've inserted the Invoke-CimMethod to many other scripts that does similar things and it works fine, like for example
Example of it working
$env:hostname
$env:process
$SessionArgs = #{
ComputerName = $env:hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = #{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession #SessionArgs
Arguments = #{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod #MethodArgs
$session = New-PSSession $env:hostname
ipconfig
Invoke-Command -Session $session -ScriptBlock {param($process) Stop-Process -ProcessName $process -Force} -ArgumentList $env:process
$Session | Remove-PSSession
Please help! I've tried everything, I even tried Get-CimSession | Remove-CimSession but that didn't work. Why is it incompatible?
I was able to fix this issue by putting the variable
$Session = New-PSSession $hostname
Right before Invoke-Command because I think when I sent enable-pssession it resets the connection.

PowerShell - Why do I have to state the New-PSSession Variable again?

So I am running an Invoke-CimMethod to push an Enable-PSRemoting command to target computer. Then run an Invoke-Command using PS-Session as a parameter. The two scripts work separately, but if I run them together I keep getting this error:
Copy-Item : The runspace state is not valid for this operation.
I had to restate the $session variable like so in order for it to run. I have bolded and highlighted the line below. My question is why?
$env:hostname = 'PC1'
$Session = New-PSSession $env:hostname
$DestinationPath = "C:\windows\temp"
$SessionArgs = #{
ComputerName = $env:hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = #{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession #SessionArgs
Arguments = #{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod #MethodArgs
Invoke-Command -Session $Session -ScriptBlock { Param($Destination) New-Item -Path $Destination -ItemType Directory -ErrorAction SilentlyContinue} -ArgumentList $DestinationPath
Copy-Item -Path "\\shared\drive\foo\bar\" -Destination "C:\windows\temp\ZScaler" -Recurse -force
############Restated here#############
$Session = New-PSSession $env:hostname
############Restated here#############
Invoke-Command -Session $session -ScriptBlock {
$msbuild = "C:\Windows\Temp\Installer\Installer.msi"
$arguments = "/quiet"
Start-Process -FilePath $msbuild -ArgumentList $arguments -Wait -Verbose
}
$Session | Remove-PSSession

How to pass variable in Scriipt Block for use with Invoke-Command that will call an executable that takes the variable as switch param

I am attempting to create a generic script that will process registry files on a list of remote servers. The script will take the input of the path/filename to process and a list of servers to process it on. Copies the .reg file to the remote server and then attempts to process the .reg file on the remote server. In order to make it generic for use with any .reg file I want to pass the path\filename to process in a variable in the script block. I have seen examples of passing named variables and positional parameters but that doesn't seem to meet my requirements. I tried creating the script block contents as a Scriptblock type and calling it but it does not work. Most of the errors I have been getting are related to invalid parsing, ambiguous parameter, etc. I have seen a couple of working examples in which the .reg file path/filename is hard-coded but that defeats the purpose of what I am attempting to accomplish. I have tried the Invoke-Command with a session and with the -ComputerName variable in order to try the :using:" command with no success. Is there any way to pass a variable that is basically the command line values (switch params & filepath/name) for an executable within the scriptblock or am I going about this in the wrong manner? In code below I am crossing domains so having to open session for those servers in order to create directory if it doesn't exist.
while ($true)
{
$regFile = Read-Host -Prompt "Enter the path & name of registry file to be processed"
If(Test-Path -Path $regFile) { break }
Write-Host "You must enter valid path & filename of a registry file to process."
}
$servers = Get-Content D:\MLB\Scripts\servers.txt
$fileNm = [System.IO.Path]::GetFileName($regFile)
$pass = ConvertTo-SecureString "blahblah" -AsPlainText -Force
$Creds = new-object -typename System.Management.Automation.PSCredential( "domain\username", $pass)
foreach ($server in $servers)
{
$dirPath = ''
$newfile = '\\' + $server + '\d$\MLB\RegFiles\' + $fileNm
if($server.ToLower().Contains("web"))
{
$Session = New-PSSession -ComputerName $server -Credential $Creds
Invoke-Command -Session $Session -ScriptBlock { New-Item -ErrorAction SilentlyContinue -ItemType directory -Path D:\MLB\RegFiles }
$newfile = "d:\MLB\RegFiles\" + $fileNm
Copy-Item $regFile -Destination $newfile -ToSession $Session -Force
Remove-PSSession -Session $Session
}
else
{
$dirPath = "\\$server\d`$\MLB\RegFiles"
New-Item -ErrorAction SilentlyContinue -ItemType directory -Path $dirPath
$newfile = "\\$server\d`$\MLB\RegFiles\$fileNm"
Copy-Item $regFile -Destination $newfile -Force
}
Invoke-Command -ComputerName $server -Credential $Creds -ScriptBlock {
$args = "s/ $newfile"
Start-Process -filepath "C:\Windows\regedit.exe" -Argumentlist $args
}

Calling param object inside script block

I am trying to create a folder remotely but the parameter that I type in command line doesn't pass in script block. Below code will only create directory webapp.
$computerName = "s3apdev0074"
Invoke-Command -ComputerName $computerName -ScriptBlock { param([string]$appname) md d:\webapp\$appname}
Please try this:
$ComputerName = 's3apdev0074'
$AppName = Read-Host "Please enter the application name"
Invoke-Command -ComputerName $ComputerName -ArgumentList $AppName -ScriptBlock {
Param (
[String]$AppName
)
# DOS:
md d:\webapp\$AppName
# PowerShell: New-Item -Path "d:\webapp\$AppName" -ItemType Directory
}
It seem you are only missing the -ArgumentList parameter to pass in your local variable.
More info here:
Get-Help Invoke-Command -Parameter ArgumentList

Global scope variable is null within Scriptblock

Running the following code produces an error because the variable used for path is resolved as null event though it defined in the script:
$ServerName = "test01"
$RemotePath = "C:\Test\"
$TestScriptBlock = { copy-item -Path $RemotePath -Destination C:\backup\ -Force -Recurse }
$CurrentSession = New-PSSession -ComputerName $ServerName
Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock
How do I call the $RemotePath defined in the parent script from within the ScriptBlock? I need to use $RemotePath in other parts of the parent script. Note, this value doesn't change, so it can be a constant.
UPDATE -- WORKING SOLUTION
You have to pass in variable as parameter to the scriptblock:
$ServerName = "test01"
$RemotePath = "C:\Test\"
$TestScriptBlock = { param($RemotePath) copy-item -Path $RemotePath -Destination C:\backup\ -Force -Recurse }
$CurrentSession = New-PSSession -ComputerName $ServerName
Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock -ArgumentList $RemotePath
You've got two scripts there, not one. The $TestScriptBlock is a separate script nested inside the main one, you send it to the remote computer, and that remote computer doesn't have $RemotePath configured. Try:
$ServerName = "test01"
$TestScriptBlock = {
$RemotePath = "C:\Test\"
copy-item -Path $RemotePath -Destination C:\backup\ -Force -Recurse
}
$CurrentSession = New-PSSession -ComputerName $ServerName
Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock
(I would probably call it $LocalPath then, though)
Try this syntax:
$globalvariable1 = "testoutput01"
$globalvariable2 = "testoutput02"
$Scriptblock = {
Write-Host $using:globalvariable1
Write-Host $using:globalvariable2
}
$serverName = Domain\HostNameofServer
Invoke-Command -ComputerName $serverName -ScriptBlock $ScriptBlock -ArgumentList $globalvariable1, $globalvariable2
The execution happens in a different session and all the variables in the current scope are not copied to the remote session by default.
You can use either parameters or "using:" as explained here:
How can I pass a local variable to a script block executed on a remote machine with Invoke-Command?