icacls.exe is not working properly on Windows 10 OS - powershell

I am working with installer which invokes icacls.exe to set folder permissions using powershell inorder to remove the "users" permission if already allowed & provides permissions for Admin & IIS users. The script is
$folderPermissionList = (Get-Acl "C:\Program Files\Workspace").Access | ?{$_.IdentityReference -match "$BUILTIN\\Users"} | Select IdentityReference,FileSystemRights
If($folderPermissionList.FileSystemRights -match "FullControl")
{
Write-Host "Inside condition"
& icacls.exe "C:\Program Files\Workspace" /Q /T /remove "BUILTIN\Users"
}
Write-Host "outside condition"
& icacls.exe "C:\Program Files\Workspace" /Q /T /grant "BUILTIN\Administrators:`(OI`)`(CI`)`(F`)"
& icacls.exe "C:\Program Files\Workspace" /Q /T /grant "BUILTIN\IIS_IUSRS:`(OI`)`(CI`)`(F`)"
The above script is working on Windows servers but it is not working in Windows 10 OS. Tried with Powershell also there is no response it is hanged in the icacls command.
Powershell version: 5.1.19041.1151
Windows 10 Enterprise [21H1]
Note: executed with elevated permission & it got stuck [refer attached results]
Any idea why it is not executing on Windows 10? or other approach to set the permissions without any issues like this?

Related

Running a Batch file using CMD as admin through Powershell

Don't ask me why, but I'm trying to run a batch file from CMD as admin by using Powershell. I have the following:
Start-Process -FilePath "cmd.exe" `
-ArgumentList "/K cd /d C:\Users\$($User)\Desktop\Activation\'win and off 2013 act.bat'" `
-Verb "runas"
The CMD opens as admin, but I get an error saying that "The system cannot find the path specified." I know it's something to do with how I've written the path to the batch file, but can't figure it out.
As I said in the comment, the quotations are at the wrong place, and I just checked, and cmd would not accept single quotes anyway. So use
"/K cd /d ""C:\Users\$User\Desktop\Activation\win and off 2013 act.bat"""

PowerShell script can't call itself because "running scripts is disabled on this system" [duplicate]

This question already has answers here:
PowerShell says "execution of scripts is disabled on this system."
(48 answers)
Closed 5 years ago.
I'm trying to write a script that installs the Linux Subsystem onto the PC. Here is the code:
function Get-ScriptDirectory { # Gets scripts full path
Split-Path -parent $PSCommandPath
}
If (-NOT ([Security.Principal.WindowsPrincipal]
[Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) #checks if script is being run as admin
{
Set-Location -Path $PSScriptRoot
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "&
{
Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy
Unrestricted -File ""Get-ScriptDirectory""' -Verb RunAs}"; # Starts
#Powershell with admin permissions and executes this script.
Break
}
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux #Installs WSL
I had to take the if statement that checks if the script is being run with system administrator privileges (can't seem to find it again). I'm also running this within a VM on a Fedora host. I think the fact that it can't call itself because "running scripts is disabled on this system" to be very strange. I took out the if statement and everything runs fine and it installs WSL.
"Running scripts is disabled..." is an indication - almost certain - that the PowerShell execution policy is set to "Restricted". See Get-Help about_Execution_Policies.
To enable running scripts, you need to run a PowerShell session as administrator, and within that session, Set-ExecutionPolicy to an execution policy that will (a) provide you with adequate security for your needs, and (b) allow you to execute scripts that you're comfortable are safe. See Get-Help Set-ExecutionPolicy.

Auto silent install by powershell

I am trying to make autoinstall my application by powershell.
I am trying like this
$command = "cmd.exe /c C:\myApp_Installer.exe /s /v /qn"
$process = [WMICLASS]"\ROOT\CIMV2:win32_process"
$process.Create($command)
Installer starts but I still must click Install button.

Copying files to a remote server in powershell

I am configuring a Jenkins job and Jenkins slave is installed in a windows server(A). I want to copy project build output folder to another windows server(B).
I can execute a batch file manually on Server A, with following content.
powershell -executionpolicy remotesigned -Command Copy-Item "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse
However, when I execute this batch file through Jenkins I get a error "Access Denied"
Access is denied
+ CategoryInfo : NotSpecified: (:) [Copy-Item], UnauthorizedAcces
sException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
erShell.Commands.CopyItemCommand
Appreciate your help..... If it is not possible via powershell, I would like to know what other alternatives I have to copy files in my Jenkins job
As admin, check if you have the -executionpolicy set as intended
powershell get-executionpolicy
if not then as admin, run:
powershell set-executionpolicy remotesigned -force
Then I am not 100% sure why you want to run this as a batch file, but instead just save it as a .ps1 file.
Copy-Item -Path "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse
where you can also use -Force -PassThru -Verbose
If you still want to run it as batch file, then just run
powershell Copy-Item -Path "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\\SYDUATAPP01\E$\build" -recurse
EDIT To run your script as admin, you can copy this into the very top of your script. It basically just creates a VBS file that launches the batch as admin. Initially it will popup the UAC prompt, but it is a once of deal, from there it will run the script as admin each time.
#echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
echo Checking privileges.
goto UPrompt
) else ( goto Admin )
:UPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\Admin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\Admin.vbs"
"%temp%\Admin.vbs"
exit /B
:Admin
if exist "%temp%\getadmin.vbs" ( del "%temp%\Admin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:----------------- Copy the rest of your Batch below this line------
#Gergard, Thank you very much for your help. I tried putting the provided bit of code to run as admin. However, nothing worked. Execution policy was remotesigned.
Finally below steps solved my problem;
I installed Powershell plugin(1.3) on my windows remote slave. Powershell 1.3, executed with "ByPass" policy
And added a step from powershell to copy item.
Copy-Item "source path" -Destination "\destination path" -recurse
Above steps didn't solve the issue and still complained as unauthorized.
Then I configured jenkins remote slave process -> properties -> run as admin account.
This solved the issue and now I am able to copy files successfully.

Installing network printers from CSV

I wrote a script to backup a users profile to a network share. My boss wants it to backup and restore network printers too. This script includes the following line of PowerShell...
Get-WMIObject -class Win32_Printer -computer $env:computername | Select Name | Export-CSV -path '\\share\printer_export.csv'
this exports all of the printers to a CSV. The values look like this.
#TYPE Selected.System.Management.ManagementObject
Name
Snagit 10
Microsoft XPS Document Writer
\\\server\printer1
\\\server\printer2
\\\server\printer3
I wrote another script to copy the users profile from the backup to the currently logged on computer. This includes the following powershell.
$PrinterList=IMPORT-CSV \\share\printer_export.csv
FOREACH ($Printer in $PrinterList) {
Invoke-Expression 'rundll32 printui.dll PrintUIEntry /in /q /n $Printer'
}
the $Printer variable should return the value \\\server\printer1 thus installing the printers from the command line... but nothing happens. Where did I go wrong?
ALSO, how can I get it to ignore any line of the CSV that does not start with "\"?
the answer below fixed the problem.
Here is the full script. It currently backs up the users profile, signatures, taskbar icons, outlook pst, chrome bookmarks, itunes mobile backups, advanced color reg settings, desktop wallpaper, exports printers to csv
REM CLOSE OUTLOOK
cscript "\\server\outlook.vbs"
REM BACKUP USERS PROFILE
xcopy "%userprofile%" "\\server\%username%\%username%" /e /y /i
REM BACKUP SIGNATURES
xcopy "%appdata%\microsoft\signatures" "\\server\%username%\Signatures" /e /y /i
REM BACKUP PINNED TASKBAR ITEMS
xcopy "%AppData%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar" "\\server\%username%\TaskBar" /e /y /i
REM BACKUP OUTLOOK ARCHIVES PST OUTLOOK MUST BE CLOSED
xcopy "C:\Users\%username%\AppData\Local\Microsoft\Outlook\*.pst" "\\server\%username%\Outlook" /y /i
REM BACKUP CHROME BOOKMARKS
xcopy "C:\Users\%username%\AppData\Local\Google\Chrome\User Data\Default" "\\server\%username%\Chrome" /e /y /i
REM BACKUP iTUNES MOBILE BACKUPS
xcopy "C:\Users\%username%\AppData\Roaming\Apple Computer\MobileSync" "\\server\%username%\MobileSync" /e /y /i
REM BACKUP ADVANCED COLOR SETTINGS
REG EXPORT "HKCU\Control Panel\Colors" "\\server\%username%\Wallpaper\Colors1.reg" /y
REM BACKUP ADVANCED COLOR SETTINGS
REG EXPORT "HKCU\Control Panel\Desktop\Colors" "\\server\%username%\Wallpaper\Colors2.reg" /y
REM BACKUP DESKTOP BG SETTINGS
REG EXPORT "HKCU\Control Panel\Desktop\WindowMetrics" "\\server\%username%\Wallpaper\WindowMetrics_Backup.reg" /y
REM START WALLPAPER BACKUP SCRIPT
Powershell.exe -executionpolicy remotesigned -File "wallpaper.ps1"
REM ASSIGNES VALUE OF CURRENT WALLPAPER TO A VARIABLE
$wallpaper = (Get-ItemProperty 'hkcu:\control panel\desktop\' -Name Wallpaper).Wallpaper
REM COPIES THE VARIABLE TO THE USERS BACKUP
xcopy $wallpaper "\\server\$env:username\Wallpaper\"
REM EXPORTS ALL CURRENTLY INSTALLED PRINTERS TO CSV
Get-WMIObject -class Win32_Printer -computer $env:computername | Select Name | Export-CSV -path '\\server\$env:username\printer_export.csv'
Here is the Restoration script. After I image a PC I run this script to put everything back.
REM CLOSES OUTLOOK
cscript "\\itmdtren\z$\backup scripts\outlook.vbs"
REM RESTORE USERS PROFILE DATA
xcopy "\\server\%username%\%username%" "%userprofile%" /e /y /i
REM RESTORE SIGS
xcopy "\\server\%username%\Signatures" "%appdata%\microsoft\signatures" /e /y /i
REM RESTORE TASKBAR ICONS, THIS LINE NOT USED
REM xcopy "\\server\%username%\TaskBar" "%AppData%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar" /e /y /i
REM RETORE OUTLOOK ARCHIVES PST
xcopy "\\server\%username%\Outlook\*.pst" "C:\Users\%username%\Documents\Outlook Files" /y /i
REM RETORE CHROME BOOKMARKS AND USER DEFAULT DATA
xcopy "\\server\%username%\Chrome" "C:\Users\%username%\AppData\Local\Google\Chrome\User Data\Default" /e /y /i
REM RESTORE iTUNES BACKUPS
xcopy "\\server\%username%\MobileSync" "C:\Users\%username%\AppData\Roaming\Apple Computer\MobileSync" /e /y /i
REM RESTORE ADVANCED BACKGROUND COLOR SETTINGS
REG import "\\itmdtren\z$\backup\%username%\Wallpaper\Colors1.reg"
REG import "\\itmdtren\z$\backup\%username%\Wallpaper\Colors2.reg"
REG import "\\itmdtren\z$\backup\%username%\Wallpaper\WindowMetrics_Backup.reg"
REM RESTORE USERS WALLPAPER USING wallpaperchanger.exe found here http://sg20.com/techblog/2011/06/23/wallpaper-changer-command-line-utility/
REM launches exe from the server, points at the wallpaper folder, randomly selects image, converts to bmp and copies it to the users theme folder then sets as wallpaper
"\\server\WallpaperChanger.exe" "\\server\%username%\Wallpaper" 2 "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Themes"
Powershell.exe -executionpolicy Unrestricted -File "PRINT.ps1"
# PRINT.ps1 looks like this
$PrinterList=IMPORT-CSV \\server\$env:username\printer_export.csv
FOREACH ($Printer in $PrinterList) {
Invoke-Expression 'rundll32 printui.dll PrintUIEntry /in /q /n $($Printer.Name)'
}
REM REFRESH USER SYSTEM PARAMETERS
RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters
Both questions are pretty simple... Where you went wrong is that when you import the CSV it created an array of objects. Each object has one property, Name. When you reference that object you need to specify the property that you want to use, so you Invoke-Expression line should be:
Invoke-Expression 'rundll32 printui.dll PrintUIEntry /in /q /n $($Printer.Name)'
That will expand the name, and it should work as expected at that point. As for getting it to skip entries that don't start with "\" you can do something like:
FOREACH ($Printer in ($PrinterList | Where{$_.Name -like "\*"})) {
That only passes entries that start with a "\" into the ForEach loop.