Practical PowerShell Uncategorized What to do without -WhatIf?

What to do without -WhatIf?

Imagine you are testing out a new script and you find a cmdlet that does not have a ‘-WhatIf’ switch available as an option. What can you do? Not much to be honest. However, you can write the cmdlet to the PowerShell window so that you know what would have been executed at that point in the script with that particular command.

Why do that? That isn’t what the -WhatIf switch does. While that is true, this tip will at least reveal what will happen if a certain part of a script were triggered. Let me illustrate with an example below.

EXAMPLE – Deleting One Drive Files

I am currently in the process of writing a scrip that will allow me to delete files in a User’s OneDrive based on the ID or the name of the file. The problem is that the cmdlet used to do so ‘ Remove-PnPListItem’ has not -WhatIf switch available.

** Note ** This cmdlet comes from the ‘SharePointPnPPowerShellOnline’ PowerShell module. Which can be found HERE.

In order to remove an item, my syntax looks like this:
[sourcecode language=”powershell”]
Remove-PnPListItem -List Documents -Identity $ID
[/sourcecode]
However, during my testing, I wanted to make sure I was deleting the correct file. I then noticed I could not use -WhatIF and decided to use Write-Host as a confirmation of what was being executed:
[sourcecode language=”powershell”]
Write-Host " Remove-PnPListItem -List Documents -Identity $ID" -ForegroundColor Red
[/sourcecode]
Now when the script gets to the part of removing the file, I see the cmdlet displayed with the ID of the file displayed. I can then confirm that the ID is the correct one. I then validate this a few times with other data to confirm it is consistent. When I am happy with the script, I can then comment out this line (preserving it for future testing) and put the one-liner for Remove-PnPListItem on a new line, like so:
[sourcecode language=”powershell”]
# Write-Host " Remove-PnPListItem -List Documents -Identity $ID" -ForegroundColor Red
Remove-PnPListItem -List Documents -Identity $ID
[/sourcecode]
Now I have a viable option for testing as well as removing files for OneDrive.

Related Post