I propose the following script for this.
Basically, you access each material in the file, then get a reference to the image texture and bsdf nodes, then create a new invert node and connect everything. You don't care about unlinking first because it will be overwritten by your new link.
import bpy
for mat in bpy.data.materials:
node_tree = mat.node_tree
if not node_tree:
continue
# Get a reference to the image and bsdf nodes
tex_image = bsdf = None
for node in node_tree.nodes:
if node.type == 'TEX_IMAGE':
tex_image = node
elif node.type == 'BSDF_PRINCIPLED':
bsdf = node
# If you have several Image Texture nodes, you can access a specific one by its name
# tex_image = node_tree.nodes.get("Image Texture") # (Or whatever the name of the image texture node connected to the roughness channel usually is)
if not (tex_image and bsdf):
continue
invert_node = node_tree.nodes.new(type='ShaderNodeInvert')
invert_node.location = (-200, 50)
tex_image.location = (-600, 50)
# Update the links. We don't care about unlinking because the current links will get overwritten
links = node_tree.links
links.new(tex_image.outputs[0], invert_node.inputs[1])
links.new(invert_node.outputs[0], bsdf.inputs["Roughness"])
