【问题标题】:change the name of of a file via powershell通过powershell更改文件名
【发布时间】:2021-09-02 12:46:27
【问题描述】:

我创建了一个 .ps1 脚本,它在多个服务器上远程运行一个 .exe 文件。该 .exe 文件创建一个 output.xml。现在我想更改它的名称,这对于每个具有随机名称的服务器都是相同的,或者是否可以使用运行该 .exe 的服务器的名称。下面你可以看到我的代码:

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 文件在 $computers 变量中定义的每台计算机上运行。 是否存在更改每个服务器的 test.xml 名称的可能性?

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    是的,您可以使用$env: 变量,点击链接了解更多信息。在这种情况下,您可以使用$env:COMPUTERNAME 来获取每个服务器的主机名:

    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
    }
    

    另一方面,您实际上并不需要 foreach 循环来遍历所有计算机。 Invoke-Command -ComputerName 参数接受一组计算机:

    $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
    

    【讨论】:

    • 您好,我测试了第二个示例,代码运行良好。谢谢!
    • @superwomen 没问题!乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 2013-07-17
    • 1970-01-01
    • 2016-01-03
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多