Search code examples
powershellpowershell-remoting

change the name of of a file via powershell


I created a .ps1 script which run remotely a .exe file on multiple servers. That .exe file create an output.xml. Now I want to change that name of it, which is the same for each server with a random name or if it is possible with the name of the server where that .exe is running. Below you can see my code:

foreach ($computers in ($computers =  Get-Content 'C:\test\comp.txt'))
 {
$server ={& 'C:\Program Files (x86)\myexe.exe' --outputfile='C:\test.xml'}
Invoke-Command -ScriptBlock $server -ComputerName $computers  
}

Myexe.exe file run on each computer defined in $computers variable. Exist the possibility to change the name of test.xml o each server ?


Solution

  • Yes, you can use the $env: variables, follow the link for more information. In this case you can use $env:COMPUTERNAME to get the hostname of each server:

    foreach ($computer in (Get-Content 'C:\test\comp.txt'))
    {
        # Note you can Append the Date too to your outfile
        # Example: "C:\$env:COMPUTERNAME - $([datetime]::Now.ToString('MM.dd.yy HH.mm')).xml"
        # Would return a filename "serverName1 - 06.17.21 13.35"
        $server ={& 'C:\Program Files (x86)\myexe.exe' --outputfile="C:\$env:COMPUTERNAME.xml"}
        Invoke-Command -ScriptBlock $server -ComputerName $computer
    }
    

    On the other hand, you don't really need a foreach loop to go through all your computers. Invoke-Command -ComputerName argument accepts an array of computers:

    $computers =  Get-Content 'C:\test\comp.txt'
    # Assuming $computers holds each hostname in a new line like
    # computername1
    # computername2
    # ...
    # ...
    
    # This should work just fine
    $server ={& 'C:\Program Files (x86)\myexe.exe' --outputfile="C:\$env:COMPUTERNAME.xml"}
    Invoke-Command -ScriptBlock $server -ComputerName $computers