Passing a password into a script - powershell

I am currently using the below PowerShell script to update an autologon value in the registry, it also checks that if the value isn't there that it is created.
Rather than opening up the script, changing the defaultpassword value in there and then running the script I'd like to be able to run the script in PowerShell and for it to prompt for the user to enter the value that is going to update.
I am new to parameters within PowerShell and can't say I'm 100% sure that is the solution.
Can anyone help? it's the 'passwordvalue' I'm looking to have inputed from a prompt and to be subsequently replaced in the script before the script runs. Let me know if I'm not being clear!
$RegKey = “HKLM:\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\WINLOGON”
if (-Not(Test-Path “$RegKey”)) {
New-Item -Path “$($RegKey.TrimEnd($RegKey.Split(‘\’)[-1]))” -Name “$($RegKey.Split(‘\’)[-1])” -Force | Out-Null
}
Set-ItemProperty -Path “$RegKey” -Name “DefaultPassword” -Type String -Value “passwordvalue”

Just use the Read-Host cmdlet:
# ....
Set-ItemProperty -Path "$RegKey" -Name "DefaultPassword" -Type String -Value (Read-Host -Prompt 'Enter the password')

Related

The requested registry access is invalid

I'm a learning System engineer and I have to Script a PowerShell Script who simply creates a Registry Key and a Value in it. I can't get it right, there is always this weird error popping up. Likewise, I already tried running it as an Administrator. Please Help!
Translation of the Error.
“The requested registry access is invalid.”
Script:
$regkey="HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Defender\Reporting"
$regparam="DisableEnhancedNotifications"
cd HKLM:\
New-ItemProperty -Path "$regkey" -Name "$regparam" -Value "test" -PropertyType "String"
Thanks!
$regkey='HKLM:\SOFTWARE\Microsoft\Windows Defender\Reporting'
$regparam='DisableEnhancedNotifications'
# create key
New-Item -Path $regkey -Force
# create entry
New-ItemProperty -Path $regkey -Name $regparam -PropertyType String -Value 'test' -Force
more examples: Working with Registry Entries (learn.microsoft.com)

Trying to export all permissions in a share using NTFSSecurity powershell module

Hi I'm attempting to export file share permissions but as is typical the file path length for a lot of our shares exceeds 260 characters.
From what I can tell the NTFSSecurity module (https://www.powershellgallery.com/packages/NTFSSecurity/4.2.4) should work past 260 character length but I don't think it's working correctly due to dir not supporting past 260 character length.
Any assistance that can get the below working with the module is appreciated.
Get-Module -ListAvailable
Import-module -name NTFSSecurity
set-location -path D:\Shares\
Dir -dir -recurse | Get-ntfsaccess |export-csv c:\temp\test.csv
If you wanna get fancy the below is a much better version prompts to enter path instead of altering the script and the policy setting at the end now waits for a Y/N input to set it instead of setting it the second it's done with the other part of the script.
$path = Read-Host "Please enter path"
$policy = get-executionpolicy
Set-executionpolicy bypass
Get-Module -ListAvailable
Import-module -name NTFSSecurity
Get-ChildItem2 -Path $Path -Recurse -Directory| Get-ntfsaccess |export-csv c:\temp\fileshareoutput.csv
$msg = 'has the file stopped growing? [Y/N]'
do {
$response = Read-Host -Prompt $msg
if ($response -eq 'y') {
Set-executionpolicy $policy
write-host 'policy set to'
write-host $policy
}
} until ($response -eq 'n')

How do I add HKCU Regkeys value for each current user in powershell script?

I want a powershell script to run each time a user login to Windows by placed in: Shell:common startup.
This script must add about 50 Regkey's in HKCU, which is setting/path for Presetfolders for a application.
I want to use Powershell and have tried this command adding the RegKey (This command needs to be repeated for each 50 regkeys!):
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$env:userprofile\Documents\AppName\Presets1' -Force
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$env:userprofile\Documents\AppName\Presets2' -Force .......
When using "$env:userprofile" instead of c:\Users\MyUserProfile\Documents\.... the -value in the RegKey will be: "$env:userprofile\Documents\NewFolder\Presets" and not as wanted: "c:\Users\MyUserProfile\Documents\NewFolder\Presets".
I need a Variable for each userprofile!
Alternatively I can after Program installation by using admin-account, I can exported all RegKey's as a .reg-file. Before using the powershell-script to merge the RegKeys everytime a user is logging in Windows, I now need to search and replace the value of the path (-Value) from AdminUserProfil-path into a variable for each user running the script.
Part of the Reg-file:
[HKEY_CURRENT_USER\Software\AppName\Version]
"HelpDocPath"="C:\Users\\AdminUserprofiles\\Documents\\AppName\\Version\\HTML Help\\en"
"ExciterCacheInstallPath"="C:\\Program Files\\AppName\\Version\\Exciter Cache"
"DSPResourceFilesInstallPath"="C:\\Program Files\\AppName\\Version/Resources"
"InstallPath"="C:\\Program Files\\AppName\\InstallFolder"
"PresetFolder"="C:\\Users\\AdminUserprofiles\\Documents\\AppName\\Version\\Presets\\Global Presets"\
Hope anyone can help?
What do I need to type for the right path, so each user will have there own path? Do I need a variable fo rusers or..?
Thank you.
Define $env:USERPROFILE as a variable so you can call it, otherwise PS will just output what you have typed, which is what is happening in this case.
$path = "$env:USERPROFILE"
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$path\Documents\AppName\Presets1' -Force

User PowerShell to get IIS Recycling Time For Remote Server

I'm trying to create a script to audit the IIS recycling times on a number of remote servers. The script I'm attempting is:
$scriptBlock = {
import-module webadministration
Get-itemproperty -Path IIS:\AppPools\WebPage -Name recycling.periodicRestart.schedule.collection}
invoke-command -computername HOSTNAME -ScriptBlock $scriptBlock
Unfortunately, this is returning absolutely nothing. Any idea what I might be doing wrong?
You are not doing anything wrong, assuming you want to query the "DefaultAppPool," what you are doing will return empty if there is no value in the collection:
Get-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule.collection
Set it with:
Set-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule -Value #{value = '03:00:00'}
And then try to get it, you will see the value.

Automate process of Disk Cleanup cleanmgr.exe without user intervention

I am developing a powershell script file which shall execute some disk cleanup without user intervention. The user shall not be able to configure anything.
When I run cleanmgr.exe /d c: sageset:1 a popup window appears to select files/folders to be cleaned(cleanup options).
This will create a registry entry containing the settings with the cleanup options and after this, you can run cleanmgr.exe /sagerun:1 which will actually execute the cleanup.
Is there a way to specify the cleanup options directly with powerhell/command line(without the need to manually select things to be deleted)?
The following Powershell script automates CleanMgr.exe. In this case, it removes temporary files and runs the Update Cleanup extension to purge superseded Service Pack Backup files (Windows 10 now does this automatically via a scheduled task). To automate other extensions, create a "StateFlags0001" property in the corresponding Registry key, as done in the New-ItemProperty lines. You will find the Registry key names in the "VolumeCaches" branch.
As far as being silent, this script attempts to start CleanMgr.exe in a hidden window. However, at some point CleanMgr spawns new processes which are visible and must be waited on separately.
Write-Host 'Clearing CleanMgr.exe automation settings.'
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' -Name StateFlags0001 -ErrorAction SilentlyContinue | Remove-ItemProperty -Name StateFlags0001 -ErrorAction SilentlyContinue
Write-Host 'Enabling Update Cleanup. This is done automatically in Windows 10 via a scheduled task.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup' -Name StateFlags0001 -Value 2 -PropertyType DWord
Write-Host 'Enabling Temporary Files Cleanup.'
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Temporary Files' -Name StateFlags0001 -Value 2 -PropertyType DWord
Write-Host 'Starting CleanMgr.exe...'
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -WindowStyle Hidden -Wait
Write-Host 'Waiting for CleanMgr and DismHost processes. Second wait neccesary as CleanMgr.exe spins off separate processes.'
Get-Process -Name cleanmgr,dismhost -ErrorAction SilentlyContinue | Wait-Process
$UpdateCleanupSuccessful = $false
if (Test-Path $env:SystemRoot\Logs\CBS\DeepClean.log) {
$UpdateCleanupSuccessful = Select-String -Path $env:SystemRoot\Logs\CBS\DeepClean.log -Pattern 'Total size of superseded packages:' -Quiet
}
if ($UpdateCleanupSuccessful) {
Write-Host 'Rebooting to complete CleanMgr.exe Update Cleanup....'
SHUTDOWN.EXE /r /f /t 0 /c 'Rebooting to complete CleanMgr.exe Update Cleanup....'
}
The PowerShell logic provided below is dynamic and ready for use or automation with the sageset options all being selected and no user interaction being required. This was inspired by multiple answers and comments from this post.
Note: I've adjusted for my needs and used successfully without any issues on multiple remote and local Windows 10 systems in particular.
Run on Local System
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' | % {
New-ItemProperty -Path $_.PSPath -Name StateFlags0001 -Value 2 -PropertyType DWord -Force
};
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' ##-WindowStyle Hidden
Run on Remote System
$cred = Get-Credential "domain\administrator";
Invoke-Command -ComputerName "computer004" {
Process {
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*' | % {
New-ItemProperty -Path $_.PSPath -Name StateFlags0001 -Value 2 -PropertyType DWord -Force
};
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -WindowStyle Hidden
}
} -AsJob -Credential $cred
Supporting Resources
cleanmgr
Invoke-Command
-AsJob
Run the command as a background job on a remote computer.
Use this parameter to run commands that take an extensive time to complete.
Get-Credential
Automate process of Disk Cleanup cleanmgr.exe without user intervention
Creating a Disk Cleanup Handler
You can use cleanmgr /verylowdisk to silently automate all the cleanup steps.
The only solution I found is to manually set the registry values like this:
...
#Set StateFlags0012 setting for each item in Windows 8.1 disk cleanup utility
if (-not (get-itemproperty -path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Active Setup Temp Folders' -name StateFlags0012 -ErrorAction SilentlyContinue)) {
set-itemproperty -path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Active Setup Temp Folders' -name StateFlags0012 -type DWORD -Value 2
set-itemproperty -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\BranchCache' -name StateFlags0012 -type DWORD -Value 2
set-itemproperty -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Downloaded Program Files' -name StateFlags0012 -type DWORD -Value 2
...
see full example
I ran into the same issue. Researching the possible ways, I have found the following:
http://stealthpuppy.com/cleaning-up-and-reducing-the-size-of-your-master-image/
It shows how to create the sageset registry settings via cmd. You can then use the sagerun:# cmd. I have not tried it via script yet, but have validated that it works...
This script will get all the Volume Caches from the Registry, enable them to be cleaned and run the CLEANMGR.EXE for all caches.
$VolumeCachesRegDir = "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
$CacheDirItemNames = Get-ItemProperty "$VolumeCachesRegDir\*" | select -ExpandProperty PSChildName
$CacheDirItemNames |
%{
$exists = Get-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name "StateFlags6553" -ErrorAction SilentlyContinue
If (($exists -ne $null) -and ($exists.Length -ne 0))
{
Set-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name StateFlags6553 -Value 2
}
else
{
New-ItemProperty -Path "$VolumeCachesRegDir\$_" -Name StateFlags6553 -Value 0 -PropertyType DWord
}
}
Start-Sleep -Seconds 3
Write-Host 'Running CleanMgr.exe...'
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:65535' -WindowStyle Hidden -PassThru
cls
Running CleanMgr.exe in a powershell script or by itself seems to work fine as long as you run it locally with an account that has local admin rights. But try running it remotely via any remote management tool or remote scripting command (Invoke-Command) and it does not run. You might see the process running on the remote system but it doesn't seem to cleanup anything and the process never ends. I would be interested if anyone has been able to get cleanmgr.exe to run remotely without any user interaction. E.G. ConfigMgr Right Click Tools, ConfigMgr App or PKG, Task Scheduler.