PowerShell远程重启IIS和Service

测试要连接的电脑开没开远程

Test-WsMan 192.168.1.1

或者直接在远程电脑查看

Get-Service WinRM

如果没开的话打开

Enable-PSRemoting –Force

连接之前需要信任远程的电脑

查看TrustedHosts列表

get-item wsman:\localhost\Client\TrustedHosts

将所有计算机都添加到TrustedHosts列表

set-item wsman:\localhost\Client\TrustedHosts -value *

将一个域里的所有计算机都添加到TrustedHosts列表

set-item wsman:\localhost\Client\TrustedHosts -value *.omg.com

将指定计算机名的计算机添加到TrustedHosts列表

set-item wsman:\localhost\Client\TrustedHosts -value <ComputerName>

将一个IP地址添加到TrustedHosts列表

set-item wsman:\localhost\Client\TrustedHosts -value 192.168.1.2

进入会话

Enter-PSSession 192.168.1.1 -Credential "OMG\admin"

分享链接

https://forsenergy.com/zh-cn/windowspowershellhelp/

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-7

https://www.pstips.net/powershell-online-tutorials

自动使用管理员身份运行

$currentWi = [Security.Principal.WindowsIdentity]::GetCurrent()
$currentWp = [Security.Principal.WindowsPrincipal]$currentWi

if( -not $currentWp.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
$boundPara = ($MyInvocation.BoundParameters.Keys | foreach{
'-{0} {1}' -f? $_ ,$MyInvocation.BoundParameters[$_]} ) -join ' '
$currentFile = (Resolve-Path? $MyInvocation.InvocationName).Path

$fullPara = $boundPara + ' ' + $args -join ' '
Start-Process "$psHome\powershell.exe"?? -ArgumentList "$currentFile $fullPara"?? -verb runas
return
}

自动实现重启IIS的Application Pool

$IP = '192.168.1.1'
$Username = 'omg\administrator'
$Password = 'laotie666'

$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

$s = New-PSSession $IP -Credential $Cred

Invoke-Command $s -ScriptBlock { Restart-WebAppPool  -Name "Test" }

自动重启远程的Service

Invoke-Command $IP -Credential $Cred -ScriptBlock { Get-Service -Name 'Test' | Restart-Service -Force }

 

你可能感兴趣的:(PowerShell)