Changing registry binary value in IF statement - powershell

I am having problem with this IF statement.
Trying to change OUTLOOK 2013 Theme. It works but the correct write-host is not working or it's not reading the value correctly.
#OUTLOOK
Push-Location
Set-Location (Join-Path 'HKCU:\Software\Microsoft\Office\15.0\Common\Roaming\Identities' -ChildPath '*companyname.com*\Settings\1170\{00000000-0000-0000-0000-000000000000}\PendingChanges' -Resolve)
$val = Get-ItemProperty -Path . -Name "Data"
if($val."Data" -eq ([byte[]](0x02,0x00,0x00,0x00)))
{
Write-Host "Microsoft Office Theme:" -NoNewline; Write-Host "....Dark Grey Theme already set..no changes needed " -ForegroundColor Green -BackgroundColor Black
Write-Output "Office theme: Dark Grey already set..no changes needed" | Out-File -FilePath "$LogPath\$env:ComputerName.log" -Append -NoClobber
} else {
set-itemproperty -Path . -Name "Data" -Value ([byte[]](0x02,0x00,0x00,0x00)) -Force
Write-Host "Microsoft Office Theme:" -NoNewline; Write-Host "....Dark Grey Theme has been set " -ForegroundColor Cyan -BackgroundColor Black
Write-Output "Office theme: Dark Grey has been set" | Out-File -FilePath "$LogPath\$env:ComputerName.log" -Append -NoClobber
}
Pop-Location
I can get it work when I change the common\'UI Theme' as that is a dword value with only a single digit. The script for that works fine, but because outlook is synced with the server, have to change the roaming identity. When I run this script, it would always say "Dark grey already set' even though it hasn't. It would change it but just wrong message.
I also had it reversed using -ne and -binary but same issue.
if($val."Data" -ne 02,00,00,00)
{
set-itemproperty -Path . -Name "Data" -Value 02,00,00,00 -Type Binary -Force
So basically, it partially works, just want to display the correct message. I am still a beginner at powershell (been only using/learning it for a week), so please be gentle. If you can tell me what I am missing or why its not working, that would be great.

Use Compare-Object to compare 2 arrays:
if ((Compare-Object $val.'Data' 2,0,0,0) -ne $null) {
Set-ItemProperty -Path . -Name 'Data' -Value 2,0,0,0 -Type Binary -Force
} else {
'Dark great already set..no changes needed'
}

Related

Powershell not able to clear IE Browsing Cookies, Caches, etc

I am trying to clear browser data from default location C:\Users\\AppData\Local\Microsoft\Windows\INetCache. I am trying to clear Cookies, Cache or any type files located in that path but I am not sure what am I missing here
screenshot
Write-Host -ForegroundColor yellow "#######################################################"
""
Write-Host -ForegroundColor Green "Powershell commands to delete cache & cookies in Firefox, Chrome & IE browsers"
Write-Host -ForegroundColor Green "By Cesar Silva"
Write-Host -ForegroundColor Green "VERSION: 3"
""
Write-Host -ForegroundColor yellow "#######################################################"
""
Write-Host -ForegroundColor Green "CHANGE_LOG:
v2.4: - Resolved *.default issue, issue was with the file path name not with *.default, but issue resolved
v2.3: - Added Cache2 to Mozilla directories but found that *.default is not working
v2.2: - Added Cyan colour to verbose output
v2.1: - Added the location 'C:\Windows\Temp\*' and 'C:\`$recycle.bin\'
v2: - Changed the retrieval of user list to dir the c:\users folder and export to csv
v1: - Compiled script"
""
Write-Host -ForegroundColor yellow "#######################################################"
""
#########################
"-------------------"
Write-Host -ForegroundColor Green "SECTION 1: Getting the list of users"
"-------------------"
# Write Information to the screen
Write-Host -ForegroundColor yellow "Exporting the list of users to c:\users\%username%\users.csv"
# List the users in c:\users and export to the local profile for calling later
dir C:\Users | select Name | Export-Csv -Path C:\users\$env:USERNAME\users.csv -NoTypeInformation
$list=Test-Path C:\users\$env:USERNAME\users.csv
""
#########################
"-------------------"
Write-Host -ForegroundColor Green "SECTION 2: Beginning Script..."
"-------------------"
if ($list) {
"-------------------"
# Clear Internet Explorer
Write-Host -ForegroundColor Green "SECTION 5: Clearing Internet Explorer Caches"
"-------------------"
Write-Host -ForegroundColor yellow "Clearing Google caches"
Write-Host -ForegroundColor cyan
Import-CSV -Path C:\users\$env:USERNAME\users.csv | foreach {
Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Microsoft\Windows\INetCache\*.*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Microsoft\Windows\WER\*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Temp\*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path "C:\Windows\Temp\*" -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path "C:\`$recycle.bin\" -Recurse -Force -EA SilentlyContinue -Verbose
}
Write-Host -ForegroundColor yellow "Done..."
""
Write-Host -ForegroundColor Green "All Tasks Done!"
} else {
Write-Host -ForegroundColor Yellow "Session Cancelled"
Exit
}
Well if any errors are occurring, you are suppressing them with the -EA SilentlyContinue flag. I would remove that from your Remove-Item calls and see if any sneaky errors are hiding there.
I'm not sure if you intended this, but in your first Remove-Item call under INetCache:
Remove-Item -path "C:\Users\$($_.Name)\AppData\Local\Microsoft\Windows\INetCache\*.*"
You are removing only files with a . in the filename, basically only files with extensions. If you want to remove everything from that directory regardless of whether it has a file extension, just use * instead of *.* as you do for your other paths.

why doesnt tee-object work with NoNewline?

i have the following function in my script
function Write-Host($object)
{
if($global:LogFile -eq $null)
{
$global:LogFile = $logFile
}
$object | tee $global:LogFile -Append
}
referencing this post: https://stackoverflow.com/a/25847258/8397835
I am trying specifically this part here:
$job = Start-Job -ScriptBlock { Start-Sleep -Seconds 10 }
while (($job.State -eq "Running") -and ($job.State -ne "NotStarted"))
{
Write-Host ([char]9632) -NoNewLine
Start-Sleep -Seconds 1
}
apparently, with tee, nonewline appears to be ignored...and without tee, i am getting the characters to display on one line as i am seeking
with tee:
without tee
I think i know whats happening. since write-host is being converted to tee, any switches are ignored, be it color or in this case, nonewline. How can i make nonewline work with tee?
After our chat I understand what you're trying to do. You want to write yourself a custom progress bar that both writes to a log file as well as to the console without line breaks in either. For that you can write a function that will accomplish it, but I do recommend picking a new name that doesn't conflict with an existing cmdlet. I'll use Write-MyProgress.
Function Write-MyProgress{
[cmdletbinding()]
Param(
[parameter(valuefrompipeline=$true)]$message,
[switch]$NoNewLine
)
if($global:LogFile -eq $null)
{
$global:LogFile = $logFile
}
Add-Content -Value $message -Path $LogFile -NoNewline:$NoNewLine
Write-Host $Message -NoNewLine:$NoNewLine
}
You could then call it explicitly:
Write-MyProgress ([char]9632) -NoNewLine
or pipe things to it:
[char]9632 | Write-MyProgress -NoNewLine
Or, if you don't want to use a function, you could just do it all with native cmdlets like in this example:
1..10 | ForEach-Object -Process {
[char]9632 | Add-Content $LogFile -NoNewLine -PassThru | Write-Host -NoNewLine
start-sleep -Sec 1
} -End {Add-Content -Value '' -Path $LogFile}
(Note that I add '' to the log file at the end, so the log file gets a new line after the progress bar is done)

How can I log everything that is written in powershell window?

I am needing to create a logfile for every action that is performed by this script.
I have attempted to use redirection(>>) however, cannot get the output to actually write to the file.
while($true){
$FromMC = Get-ChildItem -Path "\\x\From MC" -Filter *.mpg
Write-Host "Checking '\\x\From MC' for files" -ForegroundColor Cyan
Write-Host $FromMC.count"Files Found" -ForegroundColor Cyan
Write-Host ""
ForEach($file in $FromMC){
try{
Move-Item -Filter 7ST* -Path $file.Fullname -Destination "\\x\programs\7TH STREET THEATER" -Verbose -Force -ErrorAction Stop
}
catch{...}
Write-Host "Pausing for"$ts.Minutes"minutes..." -ForegroundColor Cyan
Write-Host "Ctrl+C to Stop"
Write-Host ""
Start-Sleep -Seconds $ts.TotalSeconds
}
I expect the output to be exactly as "-verbose" outputs into the shell. Types of output: Write-Host, Verbose, Write-Warning
I feel the solution is extremely simple, and I am just overlooking it.
To log everything that would normally be written to the console, like -verbose you can use Start-Transcript and when you are finished Stop-Transcript.
Example:
Start-Transcript -Path "C:\logs.txt"
#run code you want to capture
Stop-Transcript

How to set sound Scheme to "No Sound" by powershell?

We are using approx 300+ Windows10 pc in our Network and we have to set sound scheme from "Windows Default" to "No sound" can it possible with Powershell ?
Here i Found
# Set Sound Schemes to no sound
Write-Host "`nSetting Sound Schemes to 'No Sound' .." -foregroundcolor Gray
$Path = "HKCU:\AppEvents\Schemes"
$Keyname = "(Default)"
$SetValue = ".None"
$TestPath = Test-Path $Path
if (-Not($TestPath -eq $True)) {
Write-Host " Creating Folder.. " -foregroundcolor Gray
New-item $path -force
}
if (Get-ItemProperty -path $Path -name $KeyName -EA SilentlyContinue) {
$Keyvalue = (Get-ItemProperty -path $Path).$keyname
if ($KeyValue -eq $setValue) {
Write-Host " The Registry Key Already Exists. " -foregroundcolor green
}
else {
Write-Host " Changing Key Value.. " -foregroundcolor Gray
New-itemProperty -path $Path -Name $keyname -value $SetValue -force # Set 'No Sound' Schemes
Get-ChildItem -Path "HKCU:\AppEvents\Schemes\Apps" | # Apply 'No Sound' Schemes
Get-ChildItem |
Get-ChildItem |
Where-Object { $_.PSChildName -eq ".Current" } |
Set-ItemProperty -Name "(Default)" -Value ""
Write-Host " The Registry Key Value Changed Sucessfully. " -foregroundcolor green
}
}
else {
Write-Host " Creating Registry Key.. " -foregroundcolor Gray
New-itemProperty -path $Path -Name $keyname -value $SetValue -force
Get-ChildItem -Path "HKCU:\AppEvents\Schemes\Apps" |
Get-ChildItem |
Get-ChildItem |
Where-Object { $_.PSChildName -eq ".Current" } |
Set-ItemProperty -Name "(Default)" -Value ""
Write-Host " The Registry Key Created Sucessfully. " -foregroundcolor green
}

Trouble with Powershell writing to registry

I'm writing a script that will modify some registry settings on Windows machines.
I'm using an If to determine if the key/property exist before writing them. It should fail and write an error if it does. This chunk is working:
$currentPath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Ext'
$pathTest = Test-Path $currentPath
Write-Host -ForegroundColor Yellow 'Testing for: ' $currentPath
If($pathTest -ne 'True')
{
New-Item -Path $currentPath -Force | Out-Null
Write-Host -ForegroundColor Green 'Created Path: '$currentPath
}
Else{
Write-Host -ForegroundColor Red $currentPath ' already exists.'
}
Write-Host -ForegroundColor Yellow 'Disabling IE Add-On Performance Notifications (DisableAddonLoadTimePerformanceNotifications):'
If((Get-ItemProperty $currentPath -Name 'DisableAddonLoadTimePerformanceNotifications' -ea 0).'DisableAddonLoadTimePerformanceNotifications')
{
Write-Host -ForegroundColor Red 'DisableAddonLoadTimePerformanceNotifications already exists'
}
Else {
New-ItemProperty -Path $currentPath -Name DisableAddonLoadTimePerformanceNotifications -PropertyType DWord -Value '1' | Out-Null
Write-Host -ForegroundColor Green 'DisableAddonLoadTimePerformanceNotifications created and set to 1'
}
It gives me this output if the key/property exists:
Testing for: HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Ext
HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\Ext already exists.
Disabling IE Add-On Performance Notifications (DisableAddonLoadTimePerformanceNotifications):
DisableAddonLoadTimePerformanceNotifications already exists
However, this chunk does not work:
$currentPath = 'HKLM:\Software\Policies\Microsoft\Internet Explorer\Main'
$pathTest = Test-Path $currentPath
Write-Host -ForegroundColor Yellow 'Testing for: ' $currentPath
If($pathTest -ne 'True')
{
New-Item -Path $currentPath -Force | Out-Null
Write-Host -ForegroundColor Green 'Created Path: '$currentPath
}
Else{
Write-Host -ForegroundColor Red $currentPath ' already exists.'
}
If((Get-ItemProperty $currentPath -Name 'EnableAutoUpgrade' -ea 0).'EnableAutoUpgrade')
{
Write-Host -ForegroundColor Red 'EnableAutoUpgrade already exists'
}
Else{
New-ItemProperty -Path $currentPath -Name 'EnableAutoUpgrade' -PropertyType DWord -Value '0' | Out-Null
Write-Host -ForegroundColor Green 'EnableAutoUpgrade created and set to 0'
}
Output if the key/property exists:
Testing for: HKLM:\Software\Policies\Microsoft\Internet Explorer\Main
HKLM:\Software\Policies\Microsoft\Internet Explorer\Main already exists.
New-ItemProperty : The property already exists.
At C:\ps\setup\2.ps1:42 char:10
+ New-ItemProperty -Path $currentPath -Name 'EnableAutoUpgrade' -Property ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceExists: (HKEY_LOCAL_MACH...t Explorer\Main:String) [New-ItemProperty], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.NewItemPropertyCommand
EnableAutoUpgrade created and set to 0
Output of the key/property does not exist:
Testing for: HKLM:\Software\Policies\Microsoft\Internet Explorer\Main
Created Path: HKLM:\Software\Policies\Microsoft\Internet Explorer\Main
Disabling IE Auto Upgrade (EnableAutoUpgrade):
EnableAutoUpgrade created and set to 0
So, it'll create the property no problem, but can't see if it already exists.It looks to me like the If is failing on this one, but I can't figure out why. It's the same as one above it. In the full script I run a total of 14 registry entries. The ones above EnableAutoUpgrade all work. The ones below EnableAutoUpgrade do not and fail with the same error.
This is happening on multiple machines all running Win8.1 and PowerShell v4.
This is a real head scratcher. Any help would be appreciated.
Try this:
$currentPath = "HKLM:\Software\Policies\Microsoft\Internet Explorer\Main"
Write-Host -ForegroundColor Yellow "Testing for: " $currentPath
If(Test-Path "HKLM:\Software\Policies\Microsoft\Internet Explorer\Main")
{
Write-Host $currentPath " already exists." -ForegroundColor 'Red'
}
Else{
New-Item -Path $currentPath | Out-Null
Write-Host "Created Path: "$currentPath -ForegroundColor 'Green'
}