Unable to Set local group policy using powershell - windows

I try to set local group policy using PowerShell. My goal is to enable
Disable changing home page settings
Below is the PowerShell script:
# Set the values as needed
$dchps_control_panel = "HKCU:\Software\Policies\Microsoft\Internet Explorer\Control Panel"
$dchps_main = "HKCU:\Software\Policies\Microsoft\Internet Explorer\Main"
$homepage = "HomePage"
$enabled = 1
$startpage = "Start Page"
$startpage_value = "www.google.com"
# Test if the Registry Key exists already
if(-not (Test-Path $dchps_control_panel) -or -not (Test-Path $dchps_main) )
{
# Create Control Panel Key to enable and Main Key
New-Item -Path $dchps_control_panel -Force
New-Item -Path $dchps_main -Force
}
# Enable Disable changing home page settings
Set-ItemProperty -Path $dchps_control_panel -Name $homepage -Value $enabled -Type DWord
#
# Set Start Page
Set-ItemProperty -Path $dchps_main -Name $startpage -Value $startpage_value -Type String
The registry keys both get created. However, when I check the "gpedit.msc" the setting still remains to disable and nothing was configured.
Thanks

Related

Change Windows Lockscreen with Powershell: Daily Wallpaper in 4k UHD with Bing Daily Wallpaper API (Powershell)

I wanted a program that changes my Wallpaper daily, but the "Daily Desktop Wallpaper"-App only can do Full-HD and the official program from Microsoft is not only Adware, but displays an ugly watermark in the bottom right corner and can't change the Lock Screen, so I made my own small script to do that (with some help) that I wanted to share so others don't have to waste their time with this (hence the long title). It uses an API from github.
To do this everyday automatically, put the following action in a Task Scheduler Task that starts daily at a specific time:
Program/script: powershell.exe
Add arguments: -executionPolicy bypass -WindowStyle hidden -File "path\to\changeDesktopToNewestInPicturesPath.ps1"
To the question:
I still have one small problem: How do I change the Lock Screen? The current implementation does not seem to work... (In comments at the end):
Also, any suggestions are very welcome, as I am still pretty new to Powershell.
$dir = "~/Pictures/DailyWallpapers"
if (-not (Test-Path -Path $dir)) {
mkdir $dir
}
$bingApiRequest = Invoke-RestMethod -Uri "https://bing.biturl.top/?resolution=3840" -ContentType "application/json" -Method Get
$fileName = $bingApiRequest.url.split("=")[-1]
Invoke-WebRequest -Uri $bingApiRequest.url -OutFile "~/Pictures/DailyWallpapers/$($fileName)"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$filepath = $latest.FullName
$code = #'
using System.Runtime.InteropServices;
namespace Win32{
public class Wallpaper{
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;
public static void SetWallpaper(string thePath){
SystemParametersInfo(20,0,thePath,3);
}
}
}
'#
add-type $code
#Desktop Wallpaper
[Win32.Wallpaper]::SetWallpaper($filepath)
# $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
# if ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
# Write-Host "changing Lock Screen..."
# #Lockscreen
# $regKey = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP'
# if (!(Test-Path -Path $regKey)) {
# $null = New-Item -Path $regKey
# }
# Set-ItemProperty -Path $regKey -Name LockScreenImagePath -value $filepath
# Set-ItemProperty -Path $regKey -Name LockScreenImageUrl -value $filepath
# Set-ItemProperty -Path $regKey -Name LockScreenImageStatus -value 1
# }

How to keep firefox bookmarks with powershell?

like in What is the difference between opening application by cmd/ps or by click? already discussed, I have the problem, that firefox does not use my bookmarks, that I copied with powershell, as long as I open/close firefox within a script.
The only chance I have is: open/close firefox manually and then overwrite bookmarks/passwords with powershell.
Also I created the profile with arguments, but as soon as firefox will be opened, firefox is creating a new profile on its own. Obviously it makes a difference, whether I open firefox by click or ps/cmd.
Does anybody has an idea, how to tell firefox which profile it shall use when the user opens firefox?
Here my code:
# Full path of the file
$appdata = $env:APPDATA
$folder = "$appdata\Custom"
$checkfile = "$folder\firstRunRestore"
#If the file does not exist, create it and execute statement.
if (-not(Test-Path -Path $checkfile -PathType Leaf)) {
try {
$null = New-Item -ItemType File -Path $checkfile -Force -ErrorAction Stop
#Create Firefox profile
$p = New-Object System.Diagnostics.Process
$p.StartInfo.UseShellExecute = $true;
$p.StartInfo.WorkingDirectory = "C:\Program Files\Mozilla Firefox";
$p.StartInfo.Filename = "firefox.exe";
$p.StartInfo.Arguments = "-CreateProfile $env:USERNAME";
$null = $p.Start()
Start-Sleep -s 10
Stop-Process -Name "Firefox"
# Wait to close all processes
Start-Sleep -s 7
# Restore files to profile
$firefox = "$env:APPDATA\Mozilla\Firefox\Profiles"
$curProfile = Get-ChildItem -Path $firefox | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$curPath = "$firefox\$curProfile"
$source = "X:\Desktop\FF-Profile"
$keydb = "key4.db"
$logins = "logins.json"
$places = "places.sqlite"
$favicons = "favicons.sqlite"
Copy-Item -Path "$source\$keydb" -Destination "$curPath" -Force
Copy-Item -Path "$source\$logins" -Destination "$curPath" -Force
Copy-Item -Path "$source\$places" -Destination "$curPath" -Force
Copy-Item -Path "$source\$favicons" -Destination "$curPath" -Force
Remove-Item $source -Force -Recurse
}
catch {
throw $_.Exception.Message
}
}

Batch Powershell User csv import and home folder creation

I'm trying to use a CSV import to create batch users but for it to also create users' home folder and profile folders but with setting permissions at the same time.
I've found a lot of helpful information online, I just don't know how to make the syntax work with what I already have which took me quite a long time to even get to.
This is my script so far for creating accounts on the domain controller and then syncing them with O365. We use a csv as we create tons of users at the same time:
Import-Csv "C:\blablabla\filename.csv" | ForEach-Object {
New-ADUser -Name $_.Name `
-GivenName $_."GivenName" `
-Surname $_."Surname" `
-DisplayName $_."DisplayName" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $_."UserPrincipalName" `
-Path $_."Path" `
-AccountPassword (ConvertTo-SecureString “Pa$$w0rd” -AsPlainText -force) -Enabled $true `
-EmailAddress $_."EmailAddress" `
-ProfilePath $_."ProfilePath" `
-HomeDrive $_."HomeDrive" `
-HomeDirectory $_."HomeDirectory" `
-ScriptPath $_."ScriptPath" `
-Server $_."Server" `
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"} `
}
Start-ADSyncSyncCycle -PolicyType Initial
All the values point to columns in the excel file which auto-complete based on a user's first and last name.
I know I'm supposed to be creating the home and profile folders and setting permissions as per the below for example, I just don't know how to make the syntax work with what I already have?
So far, the values only get set in AD correctly but the folders don't get created and permissions aren't getting applied.
I guess I could just add an other command to create a new folder but I wouldn't know how to do append that to the foreach command?
New-Item -ItemType Directory -Path \\dc\userdata
$ACL = (Get-ACL -Path $HomeDirectory)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule([System.Security.Principal.NTAccount]"hcc.local\$UserName","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $HomeDirectory $ACL
Any help would be greatly appreciated.
Thanks.
So, as per what NAS said, something like this then
?
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"}
New-Item -ItemType Directory -Path $_.HomeDirectory
New-Item -ItemType Directory -Path $_.ProfilePath
$ACL = (Get-ACL -Path $_.HomeDirectory)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)",
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.HomeDirectory $ACL
$ACL = (Get-ACL -Path $_.ProfilePath)
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)",
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.ProfilePath $ACL
Import-Csv "C:\blablabla\filename.csv" | ForEach-Object {
New-ADUser -Name $_.Name `
...
-OtherAttributes #{ProxyAddresses= $_."ProxyAddresses"} # Remove backtick
New-Item -ItemType Directory -Path $_.HomeDirectory # create home path if needed
New-Item -ItemType Directory -Path $_.ProfilePath # create profile path if needed
$ACL = (Get-ACL -Path $_.HomeDirectory) # No need for quotes around properties if they do not contain spaces or other special characters
$FullControlAccessRule = (New-Object System.Security.AccessControl.FileSystemAccessRule(
[System.Security.Principal.NTAccount]"hcc.local\$($_.samAccountName)", # replace $UserName with correct variable
"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"))
$ACL.AddAccessRule($FullControlAccessRule)
Set-ACL -Path $_.HomeDirectory $ACL
# -> # repeat for profile path if needed
}

Change the Show Hidden Items setting on a folder

Where is the setting to "show / hide items" on a particular folder stored?
I looking to be able to change it programmatically, hopefully in Powershell.
So try this :
$file = "c:\temp\t.txt"
# Hidde $file
Set-ItemProperty -Path $file -Name attributes -Value ([io.fileattributes]::Hidden)
# Remove Hidden if set
Set-ItemProperty -Path $file -Name attributes -Value ((Get-ItemProperty $file).attributes -bxor ([io.fileattributes]::Hidden))
I try you're code but this part doesn't work:
Set-ItemProperty -Path $file -Name attributes -Value ((Get-ItemProperty $file).attributes -bxor ([io.fileattributes]::Hidden))
I just replace "hiden" by "normal" and it's work:
Set-ItemProperty -Path $file -Name attributes -Value ([io.fileattributes]::Normal)
Thank you.

Set proxy settings and proxy authentication

I'm new to PowerShell, and I'm tired of changing proxy settings and proxy authentication every time I go to the university, is there a way to do that using PowerShell Commands , like using PowerShell script to enter the proxy address and the port and the authentication, instead of using the graphical windows InternetOptions>Connections>LanSettings (I assume that exists), if yes how can I do it?
I've searched the web and StackOverflow but I had different answers that didn't target what I want.
I was interested, so I wrote a little POSH CmdLet that should help. There were plenty of references via a search on Google for how to do this so the information was there. Most of the solutions I found weren't really in the standard Powershell coding convention so I couldn't help myself. Try this out. This does nothing for the "Automatically Detect Settings". You are on your own for that one. This does however Enable/Disable proxy settings:
function Modify-ProxySettings() {
[CmdLetBinding(SupportsShouldProcess=$True)]
Param (
[Parameter(Mandatory=$False)][String]$Proxy,
[Parameter(Mandatory=$False)][String]$Port,
[ValidateSet("Disable","Enable")]
[Parameter(Mandatory=$True)][String]$Action
)
Begin {
$RegKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
if ($Action.Equals("Enable") -and ([String]::IsNullOrEmpty($Proxy) -and [String]::IsNullOrEmpty($Port))) {
throw New-Object System.Exception "Proxy and Port must be defined when enabling"
}
}
Process {
if ($Action.Equals("Enable")) {
Set-ItemProperty -Path $RegKey -Name ProxyEnable -Value 1
Write-Verbose -Message "Set: $RegKey\ProxyEnable to Enabled(1)"
Set-ItemProperty -Path $RegKey -Name ProxyServer -Value "$Proxy`:$Port"
Write-Verbose -Message "Set: $RegKey\ProxyServer to $Proxy`:$Port"
Write-Host "Proxy Enabled with $Proxy`:$Port"
} elseif ($Action.Equals("Disable")) {
Set-ItemProperty -Path $RegKey -Name ProxyEnable -Value 0
Write-Verbose -Message "Set: $RegKey\ProxyEnable to Disabled(0)"
Set-ItemProperty -Path $RegKey -Name ProxyServer -Value ""
Write-Verbose -Message "Proxy server and port removed"
Write-Host "Proxy Disabled"
}
}
}
Usage:
Modify-ProxySettings -Action Disable #Disables
Modify-ProxySettings -Action Enable -Proxy someproxy.com -Port 1337 #Enables
Some validation catches:
Action is mandatory and only takes "Disable" or "Enable". Use tab completion for simplicity
Proxy and Port are required if "Enable" is chosen

Resources