我很难在powershell中捕获净使用异常。
foreach ($k in $file){
try{
net use \\$k\share $password /USER:$username > null
Copy-Item D:\setup.exe \\$k\share
net use \\$k\share /delete > null
write-host "Copied file to \\$k\share"
}
catch [System.Exception]{
continue
}
}
如果脚本无法对机器进行身份验证,我希望脚本以静默方式继续,但我得到以下错误
net : System error 1326 has occurred.
At D:\Script\log_into.ps1:25 char:17
+ net use \\$k\share $password /USER:$username > null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (System error 1326 has occurred.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The user name or password is incorrect.
net : The network connection could not be found.
At D:\Script\log_into.ps1:27 char:17
+ net use \\$k\share /delete > null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The network con...d not be found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
答案 0 :(得分:2)
使用PowerShell cmdlet映射驱动器,以便您可以正确捕获任何异常。
这只适用于PowerShell 3.0及更高版本,因为旧版本中的-Credential
参数存在错误(它不起作用)。如果您需要兼容v2,请发表评论&我会更新。
$userPass = ConvertTo-SecureString "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $userPass
foreach ($k in $file){
try{
New-PSDrive -Name Z -PSProvider FileSystem -Root \\$k\share -Credential $Credential;
Copy-Item D:\setup.exe Z:\
Remove-PSDrive -name Z
write-host "Copied file to \\$k\share"
}
catch [System.Exception]{
continue
}
}
答案 1 :(得分:1)
尝试引用$ LASTEXITCODE值。
所以这样的事情可行。
Try
{
# Set the credentials for the destination server
Write-Output "net use starting"
net use \\$k\share $password /USER:$username > null
if ($LASTEXITCODE -eq 0) {
write-host "net use successful"
} else {
write-error "Error non zero net use exit code."
throw $error[0].Exception
}
}
Catch
{
write-error "Error setting the remote server credentials.Halting the script."
throw $error[0].Exception
}
此解决方案是通过阅读这些查询构建的:
How to obtain exit code when I invoke NET USE command via Powershell?