我有一个小的 Powershell 脚本,它创建了包含 New-PsDrive 和 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
当我执行它时,我得到了这个,它永远不会结束......它停留在运行状态:
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
28 Job28 BackgroundJob Running True localhost ...
当我在没有 Job 的情况下执行 时,它 工作 :
$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
有人可以解释我为什么吗?我在谷歌上搜索了很多,但找不到任何解释..
谢谢你的帮助
最佳答案
我是这样解决的:
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
我使用
Net-use
而不是 New-Psdrive。我认为远程 Psdrive 和 powershell 作业存在错误。
该作业完全有可能没有足够的上下文来使用
New-PsDrive
cmdlet 映射驱动器我也会在https://connect.microsoft.com/PowerShell/Feedback上报告
关于windows - 使用 New-PsDrive 时 Powershell 作业卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25873217/