From the Super Mario Wiki
Space Junk are special platforms appearing in Super Mario Galaxy and Super Mario Galaxy 2. They come in different varieties, including red or brown octagons, purple cubes, and green and blue rectangular platforms, which are the most common. Normally, they will float around randomly in space; however, when Mario or Luigi comes near them, they will suddenly move into place around him, creating a path for him above a bottomless pit.
In Super Mario Galaxy, they appear in the Space Junk Galaxy and Bowser's Galaxy Reactor. In Space Junk Galaxy, Mario encounters many of these platforms at the end of the first mission. These platforms branch out into five different pathways, each one holding a Silver Star at the end. Mario has to traverse the Cosmic Platforms and collect the five Silver Stars to form a Power Star. Mario also finds Cosmic Platforms in the Speedy Comet mission and Purple Comet mission for that galaxy, as both missions involve the same Cosmic Platform area. The format for the Cosmic Platform path is different in the Purple Comet mission, to accommodate the 100 Purple Coins.
In Bowser's Galaxy Reactor, Space Junk appears in the Ice Planet and fifth area, and are the only way to traverse both areas. This Space Junk is different, as they are fragile and will shatter several seconds after making the path. In the Ice Planet, the Space Junk is cube-shaped and made of ice, as Mario can skate on them. In the fifth area, which is comprised almost entirely of Space Junk floating in space, has platforms that are shaped like a rectangular prism. Mario must walk along these platforms in 2-D, while avoiding Firebars and encountering Gravity Walls.
In Super Mario Galaxy 2, Space Junk appears in the Cloudy Court Galaxy and Rolling Masterpiece Galaxy. Space Junk appears only in the Cosmic Clones mission in Cloudy Court Galaxy, where they form paths for Mario in lieu of the Cloud Flower. Mario also encounters Space Junk acting as walls, as Mario needs to Wall Jump up a specific area instead of using clouds. Only the green-and-blue rectangular variety of Space Junk appeared here.
In the Rolling Masterpiece Galaxy, Space Junk appears on the Palette Planet. Mario must ride the Star Ball across a short pathway of these platforms. Again, only the green-and-blue rectangular variety appear here.