PowerShell帮助-隐藏错误[新手]



我试图找到用户在Sharepoint中可以访问的所有网站,为此我正在运行下面的脚本,但是,我知道用户在某些网站中没有访问的网站,它会返回一个错误。

有没有办法隐藏错误,而代码正在运行?我尝试了几个选项,但都不起作用。

$arr = @(); get-sposite | %{ $user = get-spouser -site $_ -loginName "user@email.com" -ErrorVariable 'MyError'; if($user.Groups.Count -gt 0){ $arr += new-object psobject -property @{site=$_.url; groups=$user.Groups} } }; $arr

误差

+ CategoryInfo          : NotSpecified: (:) [Get-SPOUser], ServerUnauthorizedAccessException
+ FullyQualifiedErrorId : Microsoft.SharePoint.Client.ServerUnauthorizedAccessException,Microsoft.Online.SharePoint.PowerShell.GetSPOUser

get-spouser : Access denied. You do not have permission to perform this action or access this feature.
No linha:5 caractere:13
+     $user = get-spouser -site $_ -loginName "name.user@email.com";
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-SPOUser], ServerUnauthorizedAccessException
+ FullyQualifiedErrorId : Microsoft.SharePoint.Client.ServerUnauthorizedAccessException,Microsoft.Online.SharePoint.PowerShell.GetSPOUser

我相信您正在寻找参数SilentlyContinue的参数-ErrorAction。您还可以对代码进行一些改进。

$arr = get-sposite | Foreach-Object{
$user = get-spouser -site $_ -loginName "user@email.com" -ErrorVariable 'MyError' -ErrorAction SilentlyContinue
if($user.Groups.Count -gt 0){
[PSCustomObject]@{
site   = $_.url
groups = $user.Groups
}
}
}
$arr

编辑

cmdletGet-SPOuser似乎没有按照它应该的方式行事并尊重-ErrorAction参数。这是一个解决方法。

$currentEA = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
$arr = get-sposite | Foreach-Object{
$user = get-spouser -site $_ -loginName "user@email.com" -ErrorVariable 'MyError'
if($user.Groups.Count -gt 0){
[PSCustomObject]@{
site   = $_.url
groups = $user.Groups
}
}
}
$ErrorActionPreference = $currentEA
$arr

@Gabriel Franco,

当你想处理错误时,使用try {...} catch {...}。如果你想忽略它们,你应该像@Doug Maurer建议的那样设置$ErrorActionPreference = "Continue" (or "SilentlyContinue")

你会把指令放在try {...} catch {...}块,而不是整个循环中,例如:

$arr = get-sposite | Foreach-Object{
try{
$user = get-spouser -site $_ -loginName "user@email.com" -ErrorVariable 'MyError'
if($user.Groups.Count -gt 0){
[PSCustomObject]@{
site   = $_.url
groups = $user.Groups
}
}
}catch{
LogWrite ($Error[0].Exception)
}      
}
p>
/html>

相关内容

  • 没有找到相关文章

最新更新