i've a very strange issue with Background Job in Powershell.
I writed 2 powershell script, the first Module.ps1 contains my function, it's very basic, It creates New Psdrive, then copy a empty file toto.txt to my server, then it executes Get-Host on my server :
Function Test-One {
[cmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$ip,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$username,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$pwd
)
Set-ExecutionPolicy Unrestricted -force
Start-Service Winrm
$shareadress = "\\$ip\c$\ISO"
$password = ConvertTo-SecureString -AsPlainText -Force -String $pwd
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession -ComputerName $ip -Credential $credentials -Authentication Credssp -EA Stop
Invoke-Command -Session $session -ScriptBlock { New-Item C:\ISO -itemtype directory | Out-Null}
New-PSDrive XEN -PSProvider filesystem -Root $shareadress -Credential $credentials -Scope global
Copy-Item -path "C:\toto.txt" -Destination 'XEN:\toto.txt' -Verbose
Write-Host "Copy finished"
Invoke-Command -Session $session -ScriptBlock {Get-Host}
$session | Remove-PSSession
}When i use itdirectly in my shell, it works :
Test-one -ip "172.22.0.100" -username "Springfield\Administrator" -pwd "MyPassword" Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- XEN FileSystem \\172.22.0.100\c$\ISO Copy finished PSComputerName : 172.22.0.100 RunspaceId : 61ff6be7-e8ff-44e6-9b39-7433ce7c64c7 Name : ServerRemoteHost Version : 1.0.0.0 ......
I have a second powershell file named Job.ps1 who call the same function in a job :
Start-Job -Scriptblock {
Import-module C:\springfield\Citrix\Module.ps1
Test-One -ip "172.22.0.100" -username "Springfield\Administrator" -pwd "Activlan2015"
}
Get-Job | Wait-Job
Get-Job | Receive-Job
Remove-Job -State Completed
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
17 Job17 BackgroundJob Running True localhost When i call it, the job never stops, it completely stuck in running status.
The file is copied on the server, but it's stuck, if i remove Copy-item and New-psdrive in
my function, the job works perfectly and Receive-job display
the result of Get-host
Can somebody help me? i Don't understand why.
I use powershell 4.0
Thanks for your help