【问题标题】:Powershell "Start-Service" cmdlet not working . Doesn't write anything to the host eitherPowershell“启动服务”cmdlet 不工作。也不向主机写入任何内容
【发布时间】:2018-02-23 23:56:57
【问题描述】:

我将此函数保存到 StartWindowsService.ps1 文件中。 我确保执行策略是“不受限制的”。我按以下方式运行此文件:

在运行下一行之前,我从服务中停止了“FAService”。这样我的函数就会启动服务。

我在 Powershell 命令提示符处运行了以下行。它不会写入任何内容,也不会启动 FASservice。我真的很傻。

C:\LocationofthisFile\ .\StartWindowsService.ps1 StartWindowsService FAService

我也试过

 function StartWindowsService{
          Param([string] $ServiceName)
          $aService = Get-Service -Name $ServiceName
          if ($aService.Status -ne "Running"){
              Start-Service $ServiceName
              Write-Host "Starting " $ServiceName " service" 
              " ---------------------- " 
              " Service is now started"
           }

          if ($aService.Status -eq "running"){ 
                 Write-Host "$ServiceName service is already started"
           }
     }

谢谢

【问题讨论】:

    标签: powershell


    【解决方案1】:

    如果您在脚本中只有一个函数,当您运行脚本时,它将启动一个新的 PowerShell 作用域,定义函数,因为这就是脚本所做的所有事情,然后退出并清除它。您作为参数传递的其他内容(函数名、服务名)都不会去任何地方,因为 脚本 不会查找它们。只有函数可以,你没有调用函数。

    一种方法是dot source 脚本是. .\thing.ps1,开头有一个点和一个空格。或者Import-Module .\thing.ps1。这些将定义函数并将其保留在您当前的范围内,因此您可以在 shell 中调用它:

    c:\path\ > . .\StartWindowsService.ps1
    c:\path\ > StartWindowsService FAService
    

    另一种方法是通过删除定义使脚本成为函数:

    Param([string] $ServiceName)
    $aService = Get-Service -Name $ServiceName
    

    然后就可以直接从文件中使用了

    c:\path\ > .\StartWindowsService.ps1 FAService
    

    并且参数转到脚本Param()部分,它就像一个函数一样工作。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多