简体   繁体   English

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

[英]How can we optimize the below PowerShell Script?

My Intention is to update sql agent service password and out putting the same to html file. 我的意图是更新sql agent服务密码,并将其输入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

Nobody answered, probably because it is not clear what "optimize" means in your context. 没有人回答,可能是因为不清楚在您的上下文中“优化”是什么意思。 The only hint I can give you, is that: 我能给你的唯一提示是:

  • you can eliminate the Where part, because you call it twice 您可以删除“位置Where部分,因为您两次调用它
  • long lines such as the last one are very hard to read. 诸如最后一行这样的长行很难阅读。 Cut them. 剪下来

Edited code: 编辑代码:

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM