我一直在尝试创建一个脚本,该脚本将检查中心位置,获取哈希值,如果它不匹配,则将其替换为中心位置的一个。
我相信我所需要的一切都到位了,但我现在遇到的问题是它不能自我替换。
这在物理上是可能的吗?
另一个脚本几乎相同,我只是添加了Write-Host以获得不同的哈希值。
#Get the current path of the running script
$mypath = $MyInvocation.MyCommand.Path
#Path of the central script for updating
$ScriptUpdateLocation = "C:UsersuserDesktopScriptsUpdate Script if update is foundUpdate from me.ps1"
#Get Hashes of the currently running script and the script specified in $ScriptUpdateLocation
$MyHash = Get-FileHash -Path $mypath
$UpdateHash = Get-FileHash -Path $ScriptUpdateLocation
if ($MyHash.Hash -cne $UpdateHash.Hash){
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$msg = "You have an outdated version of this script, would you like to update?"
$wshell = New-Object -ComObject Wscript.Shell
$UpdatingScript = $wshell.Popup($msg,0,"Alert",64+4)
If($UpdatingScript -eq 7){
Copy-Item -Path $ScriptUpdateLocation -Destination $mypath -Force
$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
}
}else{
Write-Host "YOU ARE THE GOODIST BOI, CONGRATS, YOU ARE UPDATED!"
Exit
}
Copy-Item
可能会给您一个错误,即文件不能用自己覆盖。尝试阅读.ps1
内容,然后Set-Content
,而不是似乎为我工作。
改变:
Copy-Item -Path $ScriptUpdateLocation -Destination $mypath -Force
:
Get-Content $ScriptUpdateLocation -Raw | Set-Content $PSCommandPath
注意您可以使用自动变量$PSCommandPath
。