使用PowerShell运行命令

问题描述 投票:-1回答:2

我想创建一个脚本,如果我在我的计算机上以管理员身份打开该脚本,它将在不同的计算机上运行命令(无需输入凭据)。我曾经制作过一个重新启动服务的脚本。我是这样做的:

 $out = "lokation\output_NoService.txt" 
 Clear-Content $out

 $data = get-content "lokation\input_PCs.txt"

 foreach($line in $data) {    
    $computer = $line.split(":")[0]   
    $ServiceName = $line.split(":")[1]    

    If ( $sObj = Get-Service-COmputerName $Computer -Name $ServiceName -ErrorAction SilentlyContinue ){
      Restart-Service -InputObj $sObj
      Write-Host "Restarting $ServiceName on $computer"    }

    Else {
      Write-Host "$ServiceName is not running on $computer"
      Add-Content $out "$computer;$ServiceName"    } }

input_PCs.txt包含计算机名称和要重新启动的服务的名称。例如:PCName:Servicename

这是我要从txt扫描PC并在txt机器上运行命令的方式。

例如,这样的命令。

从C驱动器运行example.exe +参数。因此:C:\ example.exe -paramaters

任何人都可以提供帮助吗?

powershell cmd command
2个回答
0
投票

这样的事情?

foreach($line in $data) {

    $computer = $line.split(":")[0]   

    Invoke-Command -ComputerName $computer -ScriptBlock {C:\example.exe -parameters}

}

为了使它正常工作,您的远程计算机上将必须存在example.exe。如果还不是这种情况,则可以在上面之前添加类似的内容

if (!(\\$computer\c$\example.exe)) {

    Copy-Item -Path "X:\path_to_file\example.exe" -Destination "\\$computer\c$" -Force

}

并且,如果您不希望它请求任何凭据,请确保您的Powershell会话已在具有访问所有计算机c驱动器访问权限的管理员用户下启动。


0
投票

Restart-Service没有用于管理远程计算机上的服务的-ComputerName参数。若要远程使用该cmdlet,可以使用

Invoke-Command -Computername $computer -ArgumentList $ServiceName -ScriptBlock { 
    param($service)
    Restart-Service -Name $service}
© www.soinside.com 2019 - 2024. All rights reserved.