Currently I have this code -
Set-ExecutionPolicy Unrestricted
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
IF ($oldname -eq $name){Exit}
Else{ Rename-computer -ComputerName $oldname -NewName "$name" -force
Start-Sleep -s 5
Restart-Computer}
And I have it set to run as a scheduled task at logon and without the If Else it works perfectly however I don't want it to run every time a user logs in because it will just be a cycle of rebooting. Any help would be greatly appreciated.
I would suggest some changes:
Set-ExecutionPolicy is unnecessary, because if the machine has started processing the script, then the executionpolicy isn't a problem. So remove that, and specify it in the powershell.exe-call instead, like: powershell.exe -executionpolicy unrestricted
Use if($oldname -ne $name) { rename-computer .... } so you can remove the else part. Much cleaner
Try running the modified script below, and report back with the output in the scriptlog.txt-file.
$logpath = "c:\scriptlog.txt"
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
"NewName is '$name'" | Out-File $logpath -Append
"OldName is '$oldname'" | Out-File $logpath -Append
IF ($oldname -ne $name){
"If-test TRUE" | Out-File $logpath -Append
Rename-computer -ComputerName $oldname -NewName $name -Force
Start-Sleep -s 5
Restart-Computer
} else { #I've added the else-part just because of logging.
"IF-test FALSE" | Out-File $logpath -Append
}
Related
I'm trying to use this function to monitor BSOD remotely I know I have to add a parameter of computername just not sure where
Function Get-BSODInfo{
try {
Invoke-WebRequest -Uri "https://www.nirsoft.net/utils/bluescreenview.zip" -OutFile "$($ENV:Temp)\bluescreeview.zip"
Expand-Archive "$($ENV:Temp)\bluescreeview.zip" -DestinationPath "$($ENV:Temp)" -Force
Start-Process -FilePath "$($ENV:Temp)\Bluescreenview.exe" -ArgumentList "/scomma `"$($ENV:Temp)\Export.csv`"" -Wait
}
catch {
Write-Host "BSODView Command has Failed: $($_.Exception.Message)"
exit 1
}
$BSODs = get-content "$($ENV:Temp)\Export.csv" | ConvertFrom-Csv -Delimiter ',' -Header Dumpfile, Timestamp, Reason, Errorcode, Parameter1, Parameter2, Parameter3, Parameter4, CausedByDriver | foreach-object { $_.Timestamp = [datetime]::Parse($_.timestamp, [System.Globalization.CultureInfo]::CurrentCulture); $_ }
Remove-item "$($ENV:Temp)\Export.csv" -Force
$BSODFilter = $BSODs | where-object { $_.Timestamp -gt ((get-date).addhours(-24)) }
if (!$BSODFilter) {
write-host "Healthy - No BSODs found in the last 24 hours"
}
else {
write-host "Unhealthy - BSOD found. Check Diagnostics"
$BSODFilter
exit 1
}
}
I'm working on an application that lists all of the installed programs on a customer's computer. I've been able to get a list based on registry keys, but it doesn't include things that were installed via the Microsoft Store. It looks like using PowerShell (based on the guidance on this page: https://mhelp.pro/how-to-uninstall-windows-apps/) I can get lists of installed applications, but what I'm getting there seems to include a lot of items that aren't in Add/Remove Programs, and I'm not sure how to reconcile the 2 sources (Add/Remove Programs and the lists of programs via PowerShell). Is there some better way I should be doing this, or is there a flag or criteria that I should be using to determine if a listed application is present in Add/Remove Programs?
Perhaps something like that did you mean ?
Refer to How to Create a List of Your Installed Programs on Windows
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize |
Out-File $outputFile -Encoding UTF8 -Force
Start-Process $outputFile
EDIT : 25/08/2020 # 18:20
Here is a Self-elevate script to get everything with admin rights :
cls
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
#$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
$CommandLine = $MyInvocation.InvocationName
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize | Out-String -Width 300 |
Out-File $outputFile -Encoding UTF8 -Force
Get-AppxPackage -AllUsers |
Out-File -Append $outputFile -Encoding UTF8 -Force
Start $outputFile
In powershell 5 but not powershell 7:
get-package
What i'm trying to do ?
Create four files in local disk in the following order.
Note : In my local machine and not in any server remotely.
Three files to be created
Restart the system
On system startup create another file
Script i have used.
get-job | remove-job -Force
function create-file {
Param ([string] $a)
$p = "D:\" + $a
Write-Host $p
if (!(Test-Path $p))
{
New-Item -path D:\$a -type "file" -value "my new text"
Write-Host "Created new file and text content added"
}
else
{
Add-Content -path D:\$a -value "new text content"
Write-Host "File already exists and new text content added"
}
}
Workflow New-ServerSetup
{
create-file "one.txt"
create-file "two.txt"
create-file "three.txt"
Restart-Computer -ComputerName $env:COMPUTERNAME -Wait
Start-Sleep -Seconds 7
create-file "four.txt"
Unregister-ScheduledJob -Name NewServerSetupResume
}
$adm = "####"
$pwd = ConvertTo-SecureString -String "####" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($adm, $pwd)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name NewServerSetupResume -Credential $cred -Trigger $AtStartup -ScriptBlock {Import-Module PSWorkflow; Get-Job -Name NewSrvSetup -State Suspended | Resume-Job}
New-ServerSetup -JobName NewSrvSetup
Issues i'm facing
The execution returns Cannot wait for local computer to restart
i'm new to powershell things if any mistakes burden me.
Thanks in advance.
Schedule a job first, then reboot without waiting.
Change a value in a winlogbeat.yml as it is passed to serveral remote servers. Here is the value to change > hosts: localhost:5044 and when script kicks off on remote server it is to change to >lp-index-QA.QA.com:9999
Here is the script I wrote.. no failures but does not pass the new value to remote server>>
#ExecutionPolicy
Set-ExecutionPolicy -Force Unrestricted
#DC = (facter datacenter) | Out-String
$DC = 'parpr1'
$QAhost = #("hosts: lp-index-QA.QA.com:9999", "`r`nhosts: localhost:5044")
$PRODhost = #("hosts: lp-index-PROD.PROD.com:9999", "`r`nhosts: localhost:5044")
$file = 'C:\winlogbeat-1.2.3-windows\winlogbeat.yml'
if ($DC -eq "QA")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index-QA.QA.com:9999"
}
if ($DC -eq "PROD")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index- PROD.PROD.com:9999"
}
# delete service if it already exists
if (Get-Service winlogbeat -ErrorAction SilentlyContinue) {
$service = Get-WmiObject -Class Win32_Service -Filter "name='winlogbeat'"
$service.StopService()
Start-Sleep -s 1
$service.delete()
}
$workdir = Split-Path $MyInvocation.MyCommand.Path
# create new service
New-Service -name winlogbeat `
-displayName winlogbeat `
-binaryPathName "`"$workdir\\winlogbeat.exe`" -c `"$workdir\\winlogbeat.yml`""
#pause 5s
Start-Sleep -s 10
#Startingserver
Start-service winlogbeat
I am trying to run a perl script whenever there is a service crash. The perl script intends to restart the service and send a mail to all the developers.
I have used windows recovery options for that, where it has an option to run a program . I have filled the required details in the command line option but the script doesn't seem to get executed. Can you please help me by sharing your knowledge on this?
Recovery tab configuration
I have tried with Restart service option and that is working fine but the run a program isn't executing the script. Am I missing something?
Any comment on this will be helpful.
I recently implemented a recovery option to run a powershell script that attempts to restart the service a defined number of times and sends an email notification at the conclusion, it also attaches a txt file with recent relevant logs.
After several attempts (and despite all the other things I have seen) The configuration of fields on the recovery tab in services is as follows:
Program: Powershell.exe
**Not C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
Command line parameters: -command "& {SomePath\YourScript.ps1 '$args[0]' '$args[1]' '$args[n]'}"
eg: -command "& {C:\PowershellScripts\ServicesRecovery.ps1 'Service Name'}"
**The $args are parameters that will be passed to your script. These are not required.
here is the powershell script:
cd $PSScriptRoot
$n = $args[0]
function CreateLogFile {
$events = Get-EventLog -LogName Application -Source SomeSource -Newest 40
if (!(Test-Path "c:\temp")) {
New-Item -Path "c:\temp" -Type directory}
if (!(Test-Path "c:\temp\ServicesLogs.txt")) {
New-Item -Path "c:\temp" -Type File -Name "ServicesLogs.txt"}
$events | Out-File -width 600 c:\temp\ServicesLogs.txt
}
function SendEmail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service failure" `
-Body "The $n service on server $env:COMPUTERNAME has stopped and was unable to be restarted after $Retrycount attempts." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function SendEmailFail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service Restarted" `
-Body "The $n service on server $env:COMPUTERNAME stopped and was successfully restarted after $Retrycount attempts. The relevant system logs are attached." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function StartService {
$Stoploop = $false
do {
if ($Retrycount -gt 3){
$Stoploop = $true
SendEmail
Break
}
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select Name, State, StartMode
if ($i.State -ne "Running" -and $i.StartMode -ne "Disabled") {
sc.exe start $n
Start-Sleep -Seconds 35
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select State
if ($i.state -eq "Running"){
$Stoploop = $true
SendEmailFail}
else {$Retrycount = $Retrycount + 1}
}
}
While ($Stoploop -eq $false)
}
[int]$Retrycount = "0"
StartService