You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
### Method 2: Using verbatim strings with single quotes
181
+
180
182
Use single quotes to start a verbatim string. The double quotes need not be escaped for powershell using the backtick. However, they do need to be escaped for the executable, using a backslash.
181
183
182
184
```PowerShell
@@ -189,6 +191,54 @@ Remember, instead of escaping, it's also possible to [feed complex content from
189
191
190
192
:::
191
193
194
+
## Using CLI for Microsoft 365 in PowerShell
195
+
196
+
CLI for Microsoft 365 by default outputs errors to stderr. Unlike other shells, PowerShell works differently as it has six distinct output streams. This behavior can lead to unexpected results, such as PowerShell continuing execution even after setting $ErrorActionPreference = "Stop". For more information on PowerShell's output streams, see [handling output and errors](https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/running-commands?view=powershell-7.5#handling-output-and-errors). To address these differences, you can use the following settings and helper function to ensure that CLI errors are treated as errors.
197
+
198
+
```PowerShell
199
+
# setting output to json
200
+
m365 cli config set --key output --value json
201
+
# changing error output to stdout
202
+
m365 cli config set --key errorOutput --value stdout
203
+
# don't show help on command failure
204
+
m365 cli config set --key showHelpOnFailure --value false
205
+
# don't print errors as plain text but as objects
206
+
m365 cli config set --key printErrorsAsPlainText --value false
if ($parsedOutput -isnot [Array] -and $null -ne $parsedOutput.error) {
223
+
throw $parsedOutput.error
224
+
}
225
+
226
+
return $parsedOutput
227
+
}
228
+
```
229
+
230
+
With the above settings and helper function, you can now use a `try/catch` block to gracefully handle errors that may occur when running CLI for Microsoft 365 commands in PowerShell.
231
+
232
+
```PowerShell
233
+
try {
234
+
m365 spo list get --webUrl "https://contoso.sharepoint.com/sites/Marketing" --title "Non Existent" | Invoke-CLICommand
235
+
}
236
+
catch {
237
+
Write-Host "Failed retrieving list." -ForegroundColor Red
238
+
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
239
+
}
240
+
```
241
+
192
242
## `@meId` and `@meUserName` tokens
193
243
194
244
CLI for Microsoft 365 contains a number of commands that require you to provide a user ID or username. If you want to pass these values for the current user, instead of looking them up, you can use the built-in tokens. With the `@meId` token you can specify the ID of the current user. Using the `@meUserName` token you can specify the username of the current user.
0 commit comments