From the Super Mario Wiki
Space Junk or Cosmic Platforms 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 the 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 the 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, pieces of Space Junk appear near the Ice Planet and in the fifth area, being the only means to traverse these areas. These platforms are different, as they are fragile and will shatter several seconds after the path is formed. Near the Ice Planet, there are cube-shaped Space Junk platforms made of ice that Mario can skate on. The fifth area is comprised almost entirely of floating Space Junk in the shape of rectangular prisms. 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.