Search code examples
windowspowershellbackground-processpowershell-3.0

Powershell Job Stuck when using New-PsDrive


I've a little Powershell script, it creates New Background Job, who contains New-PsDrive and Copy-Item.

Start-Job -ScriptBlock {

$shareadress = "\\172.22.0.100\c$"
$username = "Springfield\Administrator"
$pwd = "MyPassword"

$password = ConvertTo-SecureString -AsPlainText -Force -String $pwd
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password

New-PSDrive TEMPO -PSProvider filesystem -Root $shareadress -Credential $credentials -Scope global
Copy-Item "C:\test.txt" -Destination "TEMPO:\test.txt"

Remove-PSDrive TEMPO

}

Get-Job | Wait-Job
Get-Job | Receive-Job

Remove-Job -State Completed

When i execute it, i got this, and it never end... it's stuck in Running State :

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
28     Job28           BackgroundJob   Running       True            localhost            ...                      

When i execute it without Job, it works :

$shareadress = "\\172.22.0.100\c$"
$username = "Springfield\Administrator"
$pwd = "MyPassword"

$password = ConvertTo-SecureString -AsPlainText -Force -String $pwd
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password

New-PSDrive TEMPO -PSProvider filesystem -Root $shareadress -Credential $credentials -Scope global
Copy-Item "C:\test.txt" -Destination "TEMPO:\test.txt"

Remove-PSDrive TEMPO

Can someone explain me why? I searched a lot on Google, but can't find any explanation..

Thanks for your help


Solution

  • This is how i resolved it :

    Start-Job -ScriptBlock {
    
    $destination = $letter+"\test.txt"
    $letter = ls function:[d-z]: -n | ?{ !(test-path $_) } | random
    $shareadress = "\\172.22.0.100\c$"
    $username = "Springfield\Administrator"
    $password = "MyPassword"
    
    Net use $letter $shareadress /user:$username $pwd | Out-Null
    
    Copy-Item "C:\test.txt" -Destination $destination
    
    Net use $letter /delete | Out-Null
    
    }
    
    Get-Job | Wait-Job
    Get-Job | Receive-Job
    
    Remove-Job -State Completed
    

    I used Net-use instead of New-Psdrive. I think there is a bug with Remote Psdrive and powershell jobs.

    It's entirely possible that the job doesn't have sufficient context to map a drive with New-PsDrive cmdlet

    I'll also report it on https://connect.microsoft.com/PowerShell/Feedback