我有一个小的 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 ...
当我没有作业执行它时,它有效:
$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 映射驱动器
关于windows - 使用 New-PsDrive 时 Powershell 作业卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25873217/