Execute PS from bat for Intune Win32 - windows

I am so confused and actually also not so familiar with PS and bat after my troubles with them.
I want to set the Lockscreen in Windows 10 with Intune through an IntuneWin file (WIN32 application).
I have a folder with the image, which I want to set, a copy.bat which should copy the image in the directory and also execute the PS file for setting the login image and a del.bat for deleting the image.
copy.bat
md %AllUsersProfile%\sz
copy /Y Wallpaper.jpg %AllUsersProfile%\sz
powershell -ExecutionPolicy Bypass -File Set-Lockscreen.ps1 -verb RunAs
del.bat
del /Y %AllUsersProfile%\sz\Wallpaper.jpg
Set-Lockscreen.ps1
$RegKeyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationLS"
$LockScreenPath = "LockScreenImagePath"
$LockScreenStatus = "LockScreenImageStatus"
$LockScreenUrl = "LockScreenImageUrl"
$StatusValue = "1"
$path = "C:\ProgramData\Elinvar"
$LockScreenImageValue = "C:\ProgramData\sz\Wallpaper.jpg"
sIf ((Test-Path -Path $path) -eq $false)
{
New-Item -Path $path -ItemType directory
}
if (!(Test-Path $RegKeyPath))
{
Write-Host "Creating registry path $($RegKeyPath)."
New-Item -Path $RegKeyPath -Force | Out-Null
}
New-ItemProperty -Path $RegKeyPath -Name $LockScreenStatus -Value $StatusValue -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $RegKeyPath -Name $LockScreenPath -Value $LockScreenImageValue -PropertyType STRING -Force | Out-Null
New-ItemProperty -Path $RegKeyPath -Name $LockScreenUrl -Value $LockScreenImageValue -PropertyType STRING -Force | Out-Null
RUNDLL32.EXE USER32.DLL, UpdatePerUserSystemParameters 1, True
I pack all these files with Microsoft Win32 Content Prep Tool and upload this in Intune as Win32 file.
Upload works, assigning to a group works, installation is successful. All good so far, I thought.
If I check the directory, the image is in %AllUsersProfile%\sz.
But when I check the reg, the entry is not set.
When I run the copy.bat file manually, It doesn't work. Only when I run it as administrator.
When I run the last line in cmd as administrator, so
powershell -ExecutionPolicy Bypass -File Set-Lockscreen.ps1 -verb RunAs
It works as well.
I think Intune is not running the script as administrator.
In Intune there is no configuration to say, run this command as administrator.
Maybe with a syntax? Does anyone know this?
Something like
copy.bat RunAs
I also export the reg file and import this with
reg import PersonalizationLS.reg
It didn't work.
I think there must be a way to execute the installation command in intune to run the script as admin.
It needs just for the last line the administrator privilege , md and copy work without administrator privileges. (same also for important reg file).

Related

Using the matched wildcards in cmd

Can we access the matched character in wildcards?
I have some files in my current directory name as Labx.pdsprj and I want to copy them to a subfolder in the same directory based on their file names such that "Lab3.pdsprj" goes to the subfolder ".//subfolder_name//lab3" as ".//subfolder_name//lab3//Lab3.pdsprj"
I was trying something like
copy Lab?.pdsprj .//subfolder_name//lab(something here to access the matched number)
Its not necessary to use the above command only, any help is appreciated.
This may seem excessive if your requirement is not to have a case difference in the filename "Lab*" and the subdirectory "lab" as indicated by #dave_thompson_085. Although, that solution presumes that the "lab*" subdirectory already exists. I could be changed to do this.
FOR %%A IN (Lab?.pdsprj) DO (
MKDIR "%%~nA"
COPY %%A .\subfolder\%%~nA\%%~nxA
)
If there must be a case difference, this could be used. This will run on a windows command-line batch-file running under cmd. If you are on a supported Windows system, PowerShell was installed with it on the system.
powershell -NoLogo -NoProfile -File "C:\src\t\Do-CopyPdsprjFiles.ps1"
=== C:\src\t\Do-CopyPdsprjFiles.ps1
Get-ChildItem -File -Filter 'Lab*.pdsprj' |
ForEach-Object {
if ($_.Name -match 'Lab(\d+).pdsprj') {
$LabNumber = $Matches[1]
$LabDir = Join-Path -Path '.' -ChildPath "lab$($LabNumber)"
if (-not (Test-Path -Path $LabDir)) { mkdir $Labdir | Out-Null }
Copy-Item -Path $_.FullName -Destination $LabDir
}
}

Powershell remove-item with a timer?

I have a script where my users get to install programs in on their computers.
the logic is -> copy from network path the installation file to the local hard drive of the computer,
run the installation file with different creds
I want to then delete the file but this code isnt good
copy-item "$path1" -Destination C:\ProgramData\ #copy from network path to local
$progyname = [System.IO.Path]::GetFileName($path1) #holding the programname.exe
Start-Process powershell -Credential $creds -workingdirectory c:\programdata\ -ArgumentList "-Command &{Start-Process $progyname -Verb RunAs}"
Remove-Item -path c:\programdata\$progyname -Force
Problem is the script will delete the item too soon, i actually want to wait for the installation to be completed and then delete the file.
what could work here?
Use the passthru parameter for start-process, save the returned ID to a variable and wait until the process is closed and youre good to delete
You can try this:
copy-item "$path1" -Destination C:\ProgramData\ #copy from network path to local
$progyname = [System.IO.Path]::GetFileName($path1) #holding the programname.exe
Start-Process powershell -Credential $creds -workingdirectory c:\programdata\ -ArgumentList "-Command &{Start-Process $progyname -Verb RunAs}"
$pro = $progynane.basename
If (!(Get-Process $pro -ErrorAction SilentlyContinue)){Remove-Item -path c:\programdata\$progyname -Force}
Or if you like you can -Wait parameter at end of Start-Process as #Lee_Dailey pointed.

Unable to execute PowerShell Script using 'Run with Powershell' option

Hi I wrote a simple powershell script to:
Create a IE shortcut to a site
Disable Mixed Code Security Verification for Java control panel
Add a few sites as trusted sites
The script runs fine when I manually copy and paste it into powershell.
However, when I save it as a .ps1 file and 'Run with Powershell' - it doesn't seemingly execute (changes aren't made).
I tried changing execution policy to Bypass but it still does not execute.
Any thoughts on how I can get the .ps1 script to execute by using 'Run with Powershell'?
This is so my users can simply run this script without having to copy and paste into powershell.
Thank you,
Asif
Here is the full script for reference:
& powershell.exe -executionpolicy bypass -file C:\Users\AZahir\Desktop\ps2.ps1
$Shell = New-Object -ComObject ("WScript.Shell")
$ShortCut = $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Jacada.lnk")
$ShortCut.TargetPath = "C:\Program Files (x86)\Internet Explorer\iexplore.exe"
$ShortCut.Arguments = "http://facebook.com"
$ShortCut.WorkingDirectory = "C:\Program Files (x86)\Internet Explorer";
$ShortCut.WindowStyle = 1;
$ShortCut.IconLocation = "C:\Program Files (x86)\Internet Explorer\iexplore.exe"
$ShortCut.Save()
Add-Content -Path "$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\deployment.properties" -Value ('deployment.security.mixcode=DISABLE')
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item bpoazusargdb01d
Set-Location bpoazusargdb01d
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.3"
Set-Location "172.30.1.3"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.49"
Set-Location "172.30.1.49"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.89"
Set-Location "172.30.1.89"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Leaving my original answer below but I've since found a more effective way without the file copy:
# 2>NUL & #powershell -nop -ep bypass "(gc '%~f0')-join[Environment]::NewLine|iex" && #EXIT /B 0
This is to be included as your first line of the powershell script, saved as a .cmd file.
Breakdown:
# 2>NUL &
This handles the batch part of our file so we can get that click-execution functionality. Since # isn't a filename or command, it throws an error we ignore with 2>NUL and skip to the next command with &.
#powershell ...
This is our call to powershell, grabbing the contents of the file (gc: Get-Content) and executing them (iex: Invoke-Expression). We use # so the command isn't echoed to the cli.
&& EXIT /B 0
This will exit the script gracefully if no errors were thrown.
If your only goal is to have a shortcut-clickable link for users to run your powershell script, you can accomplish that with this by pasting your script contents under this header (saved as myscript.cmd or whatever you want to name it):
::<#
#ECHO OFF
REM https://stackoverflow.com/questions/3759456/create-a-executable-exe-file-from-powershell-script#answer-4629494
REM https://blogs.msdn.microsoft.com/zainala/2008/08/05/using-0-inside-the-batch-file-to-get-the-file-info/
SET "pwsh=%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe"
SET "args=-NoProfile -NoLogo -ExecutionPolicy Bypass -Command"
SET "cmd="#(Get-Content -Path '%~f0') -replace '^^::'^|Set-Content -Path '%~dpn0.ps1';. '%~dpn0.ps1' %*""
%pwsh% %args% %cmd%
DEL "%~dpn0.ps1" /Q /F
EXIT
::#>
Simply put, it handles the execution policy and saves itself as a powershell script after replacing the batch-parts as a block comment.
This is so my users can simply run this script without having to copy
and paste into powershell.
Use a bat file side by.
include
PowerShell.exe -executionpolicy bypass -file "%~dp0ps2.ps1"
Remove below from your powershel script.
& powershell.exe -executionpolicy bypass -file C:\Users\AZahir\Desktop\ps2.ps1
When a user double clicks the bat file, they will run the ps2.ps1.
I don't see errors , when i run it . It creates the shortcut and the reg keys. In case, if you are trying to run it second time, it will generate errors saying the reg keys exists..
Also its wise to use """ instead of " more details How to pass msi ArgumentList with $ScriptDir with spaces in powershell?
or else your users may find difficulties running your script, if they put this script in a path with space such as c:\new folder\

I want to remove all contents of %temp% directory wihout any confirmation

I just want to delete %temp% folder of that particular user that is currently logged in without any confirmation using a PowerShell script.
This is what I have tried so far:
$tempRM = #("C:\Users*\Appdata\Local\Temp*")
Remove-Item -Path $tempRM -Recurse -Force
OS will be mostly server 2003,2008,2012 and above.
Use the $env:TEMP environment variable to determine the temp path and delete it using the Remove-Item cmdlet with the -ErrorAction parameter set to SilentlyContinue to supress any potential errors:
Remove-Item -Path $env:TEMP -Recurse -Force -ErrorAction SilentlyContinue

How to run a PowerShell script from a batch file

I am trying to run this script in PowerShell. I have saved the below script as ps.ps1 on my desktop.
$query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"
Register-WMIEvent -Query $query -Action { invoke-item "C:\Program Files\abc.exe"}
I have made a batch script to run this PowerShell script
#echo off
Powershell.exe set-executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
pause
But I am getting this error:
You need the -ExecutionPolicy parameter:
Powershell.exe -executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.
I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here.
This is basically what you are looking for:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
And if you need to run your PowerShell script as an admin, use this:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Users\SE\Desktop\ps.ps1""' -Verb RunAs}"
Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.
If you want to run from the current directory without a fully qualified path, you can use:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
It is better to use Bypass...
Small sample test.cmd
<# :
#echo off
powershell /nologo /noprofile /command ^
"&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(#(&{$args}%*))}"
exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...
Posted it also here:
How to run powershell command in batch file
Following this thread:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch
you can convert any PowerShell script into a batch file easily using this PowerShell function:
function Convert-PowerShellToBatch
{
param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string]
[Alias("FullName")]
$Path
)
process
{
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
$newPath = [Io.Path]::ChangeExtension($Path, ".bat")
"#echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
}
}
To convert all PowerShell scripts inside a directory, simply run the following command:
Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
Convert-PowerShellToBatch
Where is the path to the desired folder. For instance:
Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
Convert-PowerShellToBatch
To convert a single PowerShell script, simply run this:
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
Where is the path to the desired file.
The converted files are located in the source directory. i.e., <FILE-PATH> or <DIR-PATH>.
Putting it all together:
create a .ps1 file (PowerShell script) with the following code in it:
function Convert-PowerShellToBatch
{
param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string]
[Alias("FullName")]
$Path
)
process
{
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
$newPath = [Io.Path]::ChangeExtension($Path, ".bat")
"#echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
}
}
# change <DIR> to the path of the folder in which the desired powershell scripts are.
# the converted files will be created in the destination path location (in <DIR>).
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
And don't forget, if you wanna convert only one file instead of many, you can replace the following
Get-ChildItem -Path <DIR> -Filter *.ps1 |
Convert-PowerShellToBatch
with this:
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
as I explained before.
If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted and then reset with Set-executionpolicy -ExecutionPolicy Default.
Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.
# Check current setting
Get-ExecutionPolicy
# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com | tee ping__google.com.txt }
# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es
Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>),
example:
#echo off
set WD=%~dp0
ECHO New-Item -Path . -Name "Test.txt" -ItemType "file" -Value "This is a text string." -Force > "%WD%PSHELLFILE.ps1"
ECHO add-content -path "./Test.txt" -value "`r`nThe End" >> "%WD%PSHELLFILE.ps1"
powershell.exe -ExecutionPolicy Bypass -File "%WD%PSHELLFILE.ps1"
del "%WD%PSHELLFILE.ps1"
Last line deletes the created temp file.
If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server - 'Configure Login script Delay' the default setting 'not configured' this will leave a 5-minute delay before running the login script.

Resources