我们如何优化以下PowerShell脚本?

时间:2011-09-03 21:13:24

标签: powershell

我的意图是更新sql代理服务密码,并将其与html文件相同。

$server = "LocalHost";$OldPass = "xyz";$NewPass = "abc"
[System.Reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null
$wmi = new-object ("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") $server
$wmi.services | where {($_.ServiceAccount -eq '.\Ramu' -and $_.Type -eq 'SQLAgent')} | foreach {$_.ChangePassword($OldPass,$NewPass)}
$wmi.services | where {($_.ServiceAccount -eq '.\Ramu' -and $_.Type -eq 'SQLAgent')} | Select-object @{label="Server";expression={$wmi.name}},Name,Type,ServiceAccount,DisplayName,@{label="Status";expression={"Passwword update completed successfully on " + (get-date).ToString()}} | ConvertTo-HTML -head $a -body "<H2>$server SQL Service Account Password Update Status</H2>" | Out-File D:\RP-TEST\Test.htm

1 个答案:

答案 0 :(得分:0)

没有人回答,可能是因为尚不清楚“优化”在您的背景下意味着什么。我能给你的唯一提示是:

  • 您可以删除Where部分,因为您将其调用两次
  • 诸如最后一行之类的长行很难阅读。切它们。

编辑代码:

$server = "LocalHost";$OldPass = "xyz";$NewPass = "abc"

Add-type "Microsoft.SqlServer.SqlWmiManagement" | out-null

$wmi = new-object ("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") $server
$wmi.services | 
    Where {($_.ServiceAccount -eq '.\Ramu' -and $_.Type -eq 'SQLAgent')} | 
    Foreach {$_.ChangePassword($OldPass,$NewPass); $_} |   # note the added $_
    Select-object @{label="Server";expression={$wmi.name}},Name,Type,ServiceAccount,DisplayName,@{label="Status";expression={"Passwword update completed successfully on " + (get-date).ToString()}} | 
    ConvertTo-HTML -head $a -body "<H2>$server SQL Service Account Password Update Status</H2>" | 
    Out-File D:\RP-TEST\Test.htm