1

I want to test if New-Item throws an error, for which i am using the -WhatIf parameter and catch the error if an error occurs. If no error occurs, i dont want the -WhatIf output in my console.

I tried the following, but the "WhatIf:"-Output still gets printed to the Powershell console:

New-Item -Path $Path -Name $Name -ItemType $ItemType -ErrorAction stop -WhatIf | Out-Null

I also tried to use $WhatIfPreference as in this StackOverflow answer, which had the same result.

Kevin Holtkamp
  • 479
  • 4
  • 17
  • `-WhatIf` doesn't do what you seem to think it does; it only outputs what *would* happen if the operation was actually *attempted*, it doesn't verify anything on its own and generally doesn't produce any kind of error at all. (Some invalid invocations *might* result in an error even with `-WhatIf`, but most won't.) For example, `New-Item /etc/x -WhatIf` on my machine happily prints that it would create a file, even though creating that file would certainly fail due to insufficient permissions. As such it's not clear what you think `-WhatIf` would bring you, here; just catch the error. – Jeroen Mostert Mar 28 '22 at 20:04
  • 1
    Also, to the best of my knowledge, `-WhatIf` output cannot be suppressed even if this was desirable for some reason (which it's not, since if you don't want it you can just not ask for it); it's written directly to the host (but not using the information stream, like `Write-Host`, so redirecting that with `6>` or `*>` won't do anything either). – Jeroen Mostert Mar 28 '22 at 20:16
  • What do you mean by "just not ask for it"? Not using the `-WhatIf` parameter? I am using it because I found no other way to do what I need, which is basically to find out if the cmdlet will throw an error or not – Kevin Holtkamp Mar 29 '22 at 18:53
  • 2
    The only way to know if the cmdlet will throw an error is to invoke it. Without `-WhatIf`. If you include `-WhatIf`, the cmdlet will not *do* anything except basic parameter validation. It won't check if the disk is full, or the medium is write-only, or if you have permission to put anything in the location, or any other potential problem that might occur if you actually tried creating the item. And if all you need is argument validation, you can do something like `Test-Path $Path` up front. – Jeroen Mostert Mar 29 '22 at 18:56

0 Answers0