PowerShell: operation is not valid
Documentation: Microsoft Learn
Inspect object state, method requirements and collection changes when PowerShell reports an invalid operation.
What it means
The requested operation is not valid for the object in its current state. A disposed connection, unsupported action or collection modification during enumeration can cause this. Inspect the exception and the actual object state before deciding what to change.
Likely causes
- A collection was modified inside a foreach loop that is still enumerating it
- A method was called on a closed or disposed object such as a broken PSSession
- A property was read that only populates after another call, as with an Azure VM PowerState when -Status was omitted
- A cast was attempted between two types that have no conversion between them
Check
Run these checks before changing anything.
What these checks establish
The useful result is the exception type, message and state of the object at the failing line. Get-Member describes that object; it cannot tell you that a previous state transition succeeded.
Fix
Identify the operation that was invalid for this state. If enumeration is invalidated by mutation, iterate an intentional snapshot or collect changes for a later pass. If a connection was disposed or closed, establish a new valid connection rather than retrying its old object. Use the state model documented for that object type.
Verify: Repeat the operation with a valid state and test the previously failing transition. Confirm the output as well as the absence of an exception.