能否将这段PowerShell脚本改写为无分号的单行命令?
PowerShell Single-Line Rewrite (No Semicolons)
Absolutely fun challenge—let's turn that multi-line script into a single, semicolon-free command using PowerShell's pipeline and nested expressions, no temporary variables needed:
Get-Mailbox "a mailbox" | ForEach-Object { Get-MailboxFolderPermission -Identity "$($_.PrimarySmtpAddress):\$(Get-MailboxFolderStatistics $_.PrimarySmtpAddress | Where-Object FolderType -eq 'Calendar' | Select-Object -First 1 -ExpandProperty Name)" -ErrorAction SilentlyContinue | Select-Object @{Label="Identity";Expression={$_.Identity}},@{Label="User";Expression={$_.User}},@{Label="AccessRights";Expression={$_.AccessRights}}}
Breakdown of how this works (for learning purposes):
- We start with
Get-Mailbox "a mailbox"to fetch the target mailbox object, then pipe it directly toForEach-Object(no need for the$mbxvariable) - Inside the
ForEach-Objectblock, we build the calendar folder identity using nested subexpressions ($()):$_.PrimarySmtpAddresspulls the mailbox's email address from the piped object- The nested
Get-MailboxFolderStatisticscall filters for the first Calendar-type folder, using-ExpandProperty Nameto grab just the folder name string instead of an object
- We pass that constructed identity to
Get-MailboxFolderPermission(with silent error handling as in your original script) - Finally, we pipe to
Select-Objectwith calculated property definitions (I filled in logical labels based on your partial script—adjust these to match your exact needs!)
This works because PowerShell's pipeline handles passing objects between commands, and nested subexpressions let us embed command output directly into strings or parameters—no semicolons required to separate statements.
内容的提问来源于stack exchange,提问作者Niklas J. MacDowall
相关产品推荐
相关产品推荐

