Creating a cmd script to save bitlocker numeric id to ad - cmd

I am trying to create a bat file to run cmd code to save bitlockers numeric id to ad
the code I got that far is
#echo off
title bitlocker to AD.
echo Bitlocker to ActiveDirectory
pause
powershell -Command manage-bde -protectors -get c:
powershell -Command manage-bde -protectors c: -id {<numericalpassword>}
echo 1)Exit
set input=
set /p input= Choice
if %input%==2 goto Exit if NOT goto Start 2```
`
But what I got when I run it is:
[![what really happened][1]][1]
[1]: https://i.stack.imgur.com/uM3b9.png
basically it cannot recognize the "<numericalpassword>"
How to I get the numerical password id as a string that I can push to the second line?

I have tested in my environment
how to i get the numerical password id as a string that i can push to
the second line ?
You can use the below command to get the numerical password id as a string variablee :
$key = ((manage-bde -protectors -get c:) | Select-String -SimpleMatch "ID: ")[1] -replace "ID:","" -replace " ",""
Now you can use this variable in the second line as follows :
manage-bde -protectors -adbackup c: -id $key
Also, you can write the powershell script for the two powershell commands and run the script in the bat file.
Use the below powershell script :
$key = ((manage-bde -protectors -get c:) | Select-String -SimpleMatch "ID: ")[1] -replace "ID:","" -replace " ",""
manage-bde -protectors -adbackup c: -id $key
Save this script in your local and use this line in your bat file :
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'path-to-your-powershell-script'"
Instead of
powershell -Command manage-bde -protectors -get c:
powershell -Command manage-bde -protectors c: -id {<numericalpassword>}

I'm getting this when I try to run:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'path-to-your-powershell-script'"
Output:
C:\Users>$key = ((manage-bde -protectors -get c:) | Select-String -SimpleMatch "ID: ")[1] -replace "ID:","" -replace " ",""
'$key' is not recognized as an internal or external command,
operable program or batch file.

Related

Saving results after a for loop in Windows CMD

I have been trying to create a line of code to ping a range of IP addresses, in the windows command prompt, and after it finishes save the results in a text file. I am using a for loop to do the pinging, but I can't figure out how to save the results in a text file.
This is what I am using:
for /l %i in (1,1,64) do #ping 10.39.63.%i -w 1500 -n 1 | find "Reply"
I tried using the following code to save results in a text file, but it only saves the last command performed by CMD:
for /l %i in (1,1,64) do #ping 10.39.63.%i -w 100 -n 1 | find "Reply" >C:\Users\brymed\Desktop\test.txt
I want to keep it simple, so it'd be awesome to use only a line of code, but I am open to suggestions. Thank you.
This is not difficult using PowerShell. The $Hosts variable is a list of IP addresses to ping. The results are written to a file.
$Hosts = #()
foreach ($i in 1..64) { $Hosts += "10.39.63.$i" }
Test-Connection -Count 1 $hosts |
Select-Object -Property Address,BufferSize,Latency,Status |
Out-File -FilePath "$Env:USERPROFILE/Desktop/test.txt" -Encoding ascii
If you -must- run this in cmd.exe, the code can be formatted to do so.
pwsh.exe -NoLogo -NoProfile -Command ^
"$Hosts = #();" ^
"foreach ($i in 1..64) { $Hosts += \"10.39.63.$i\" };" ^
"Test-Connection -Count 1 $hosts -ErrorAction SilentlyContinue |" ^
"Select-Object -Property Address,BufferSize,Latency,Status |" ^
"Out-File -FilePath "$Env:USERPROFILE/Desktop/test.txt" -Encoding ascii"
Get PowerShell Core from https://github.com/PowerShell/PowerShell

Windows powershell error when modifying windows service parameter

I am trying to update one of the parameters of Windows Service (kubelet) by using this link
1. $regkey = "HKLM\SYSTEM\CurrentControlSet\Services\kubelet"
2. $name = "ImagePath"
3. $(reg query ${regkey} /v ${name} | Out-String) -match "(?s)${name}.*(C:.*kubelet\.exe.*)"
4. $kubelet_cmd = $Matches[1] -replace "--image-pull-progress-deadline=.* ","" -replace "\r\n"," "
5. reg add ${regkey} /f /v ${name} /t REG_EXPAND_SZ /d "${kubelet_cmd} --image-pull-progress-deadline=40m "
Step #3 output
PS C:\Users\Administrator> $(reg query ${regkey} /v ${name} | Out-String) -match "(?s)${name}.*(C:.*kubelet\.exe.*)"
True
Output of Steps 4 and 5
PS C:\Users\Administrator> $kubelet_cmd = $Matches[1] -replace "--image-pull-progress-deadline=.* ","" -replace "\r\n"," "
PS C:\Users\Administrator> reg add ${regkey} /f /v ${name} /t REG_EXPAND_SZ /d "${kubelet_cmd} --image-pull-progress-deadline=40m "
ERROR: Invalid syntax.
Type "REG ADD /?" for usage.
I am not sure which part of reg add is causing this error. Kindly let me know what am I doing wrong
EDIT
Output of $kubelet_cmd is given below
PS C:\Users\Administrator> echo $kubelet_cmd
C:\ProgramData\Kubernetes\kubernetes\node\bin\kubelet.exe --windows-service --v=6 --log-dir=C:\ProgramData\Kubernetes\logs\kubelet --cert-dir=C:\var\lib\kubelet\pki --cni-bin-dir=C:\ProgramData\Kubernetes\cni --cni-conf-dir=C:\ProgramData\Kubernetes\cni\config --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --hostname-override=WIN --pod-infra-container-image=mcr.microsoft.com/k8s/core/pause:1.2.0 --enable-debugging-handlers --cgroups-per-qos=false --enforce-node-allocatable="" --logtostderr=false --network-plugin=cni --resolv-conf="" --cluster-dns="10.96.0.10" --cluster-domain=cluster.local --feature-gates=
It appears some of the attributes have double-quotes which is causing the issue. But, not sure how to overcome this when executing Step #5
I resolved the steps by editing Windows registry
Opened Windows registry
Navigated to Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\kubelet hive
Right-click --> Modify on attribute ImagePath (on the right pane)
Added the parameter --image-pull-progress-deadline=50m
Restarted kubelet service using services.msc

How to read a variable inside a powershell command written in a .bat file

I have this bat file that i execute and it works great:
SET RPPROPERTIESPATH='C:\work\filepath.txt' //contains the word 'string1'
powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', 'string2' | Out-File -encoding ASCII %RPPROPERTIESPATH%"
But i want the replace param to come from a variable like so:
SET RPPROPERTIESPATH='C:\work\filepath.txt' //contains the word 'string1'
SET STRINGTOREPLACE='string3'
powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', %STRINGTOREPLACE% | Out-File -encoding ASCII %RPPROPERTIESPATH%"
This is not working, how should i make this work?
Set variables using set "varname=varvalue" syntax pattern and use them quoted if necessary like "%varname%" (for cmd) or like '%varname%' (for PowerShell). Then, your code snippet should be as follows:
SET "RPPROPERTIESPATH=C:\work\filepath.txt" //contains the word 'string1'
SET "STRINGTOREPLACE=string3"
powershell -Command "(gc '%RPPROPERTIESPATH%') -replace 'string1', '%STRINGTOREPLACE%' | Out-File -encoding ASCII '%RPPROPERTIESPATH%'"
Seems to work once i exclude the ' like so:
SET STRINGTOREPLACE=string3
powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', '%STRINGTOREPLACE%' | Out-File -encoding ASCII %RPPROPERTIESPATH%"

How to break up a long string in multiple lines in a windows batch file while still allow cmd.exe to parse it as a single argument?

I have a Windows batch file for cmd.exe. It has a single line of code to invoke the PowerShell Send-MailMessage cmdlet and exit back to cmd.exe. Currently the line reads like:
PowerShell -Command "Send-MailMessage -To one.person#somewhere.com, another.person#sameplace.com -Subject 'A rather lengthy text' -From info#my.com -SmtpServer hostname.subdomain.mycompany.com -UseSsl -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'UserName',('SecretePassword1234'|ConvertTo-SecureString -AsPlainText -Force)) -Body 'A static text.'"
It works great. But I find it difficult to edit it in NotePad or any text editor because the line is way too long. What I want is to use the CMD.EXE's caret ^ character to break up the long string within the double quotes into multiple lines. However, the PowerShell.EXE command requires that:
PowerShell -Command <string>
The above syntax requires that CMD.EXE parse everything after -Command to be a SINGLE string, aka a single argument. I've tried the following that didn't work:
PowerShell -Command "Semd-MailMessage Blab Blab " ^
"More Blah Blah"
If I break up the line in my batch file as above, CMD.EXE will parse the first part of the string as one argument, and the string on the next line as another argument. Wrong. So what should I do?
I would put your command into a powershell script and then call that from cmd using the following command (or something similar):
powershell.exe -noprofile -executionpolicy bypass -file "path to my file.ps1"
then your editing can all happen inside the powershell ide and you can split your command up as required; either by using variables and/or by using the ` (back tick) character. Your Powershell script could then look like the following with is a lot easier to manage; plus you get the benefit of intellisense as you edit the script:
Send-MailMessage `
-To one.person#somewhere.com, another.person#sameplace.com `
-Subject 'A rather lengthy text' `
-From info#my.com `
-SmtpServer hostname.subdomain.mycompany.com `
-UseSsl `
-Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'UserName', ('SecretePassword1234'|ConvertTo-SecureString -AsPlainText -Force)) `
-Body 'A static text.'
I can agree as you've indicated that this doesn't work:
PowerShell -Command "Semd-MailMessage Blab Blab " ^
"More Blah Blah"
…and also agree that this doesn't either:
#Echo Off
PowerShell -Command "Get-WmiObject -Class Win32_Product "^
"| Select-Object -Property Name | Sort-Object Name"
Pause
However this does:
#Echo Off
PowerShell -Command "Get-WmiObject -Class Win32_Product "^
"| Select-Object -Property Name | Sort-Object Name"
Pause
…note the very small but seemingly very important single space at the beginning of the continuation line!
I think this is the simplest and clearest way to solve this problem because this method does not require additional files nor additional options, just plain PowerShell code:
PowerShell ^
Send-MailMessage ^
-To one.person#somewhere.com, another.person#sameplace.com ^
-Subject 'A rather lengthy text' ^
-From info#my.com ^
-SmtpServer hostname.subdomain.mycompany.com ^
-UseSsl ^
-Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'UserName',('SecretePassword1234'^|ConvertTo-SecureString -AsPlainText -Force)) ^
-Body 'A static text.'
Just be sure to properly escape special Batch characters, like ^|.
You either set variables in a batch file or you can do something completely hokey like this.
#echo off
setlocal enabledelayedexpansion
set "pscommand="
FOR %%G IN (
"Send-MailMessage -To one.person#somewhere.com, "
"another.person#sameplace.com "
"-Subject 'A rather lengthy text' "
"-From info#my.com "
"-SmtpServer hostname.subdomain.mycompany.com "
"-UseSsl -Credential "
"(New-Object -TypeName System.Management.Automation.PSCredential "
"-ArgumentList 'UserName',('SecretePassword1234'|ConvertTo-SecureString -AsPlainText -Force)) "
"-Body 'A static text.'"
) DO (
set "pscommand=!pscommand!%%~G"
)
PowerShell -Command "%pscommand%"

Starting a batch file from PowerShell with arguments

Based on How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required? I'm trying to make an RunElevated.bat (see code below) that accepts a command-line (batch file name and parameters) as arguments.
The RunElevated.bat works fine when the target batch file path has no spaces in them. But it fails as soon as that path has spaces: no matter how I quote things, either PowerShell barfs, or the parameters are not passed correctly from PowerShell to the batch file.
I tried:
escaping with "" (as suggested by many sources)
escaping with \" (as suggested by Escaping quotes in powershell.exe -command via command prompt)
adding --% (as suggested by PowerShell and external commands done right and Easier Reuse of Command Lines From Cmd.exe)
surrounding with ' (as suggested by CB.).
So:
Is what I want to do possible at all?
If so: how?
RunElevated.bat:
:checkParameters
echo [%*]
if [%1]==[] ( goto :help ) else ( goto :checkPrivileges )
:help
echo Syntax:
echo %0 CmdLine
echo Where CmdLine is executed with UAC privileges.
goto :exit
:checkPrivileges
net file 1>nul 2>nul
if '%errorlevel%' == '0' ( goto :gotPrivileges ) else ( goto :getPrivileges )
:getPrivileges
PowerShell "Start-Process -FilePath \"%0\" -Verb RunAs -ArgumentList \"%*\""
goto :exit
:gotPrivileges
%*
pause
:exit
pause
exit /b
echo-cd.bat which I stored in both D:\tools\echo-cd.bat and "D:\to ols\echo-cd.bat":
echo Current Directory: [%CD%]
echo Parameters: [%*]
pause
This runs fine:
D:\tools\RunElevated.bat D:\tools\echo-cd.bat foo
These fail:
D:\tools\RunElevated.bat "D:\to ols\echo-cd.bat" foo
First failure is at the %*:
C:\Windows\system32>D:\to ols\echo-cd.bat foo
'D:\to' is not recognized as an internal or external command,
operable program or batch file.
This is because PowerShell removed the quotes around the batch file name:
C:\Windows\system32>echo [D:\to ols\echo-cd.bat foo]
[D:\to ols\echo-cd.bat foo]
I expected D:\to ols\echo-cd.bat to have double quotes around it, and foo not.
D:\tools\RunElevated.bat \"D:\to ols\echo-cd.bat\" foo
Second failure is at the PowerShell level:
D:\>PowerShell "Start-Process -FilePath \"D:\tools\RunElevated.bat\" -Verb RunAs -ArgumentList \"\"D:\to ols\echo-cd.bat\" foo\""
Start-Process : Cannot validate argument on parameter 'ArgumentList'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
At line:1 char:77
+ Start-Process -FilePath "D:\tools\RunElevated.bat" -Verb RunAs -ArgumentList <<<< ""D:\to ols\echo-cd.bat" foo"
This is because escaping twice will end up with an empty string for ArgumentList.
D:\tools\RunElevated.bat --% "D:\to ols\echo-cd.bat" foo
Third failure is also at the %*:
C:\Windows\system32>--% D:\to ols\echo-cd.bat foo
'--%' is not recognized as an internal or external command,
operable program or batch file.
This too is because PowerShell removed the quotes around the batch file name:
C:\Windows\system32>echo [--% D:\to ols\echo-cd.bat foo]
[--% D:\to ols\echo-cd.bat foo]
I expected --% to be absent, D:\to ols\echo-cd.bat to have double quotes around it, and foo not.
D:\tools\RunElevated.bat '"D:\to ols\echo-cd.bat"' foo
Again a failure is at the %*:
C:\Windows\system32>'D:\to ols\echo-cd.bat' foo
The filename, directory name, or volume label syntax is incorrect.
This is because PowerShell removed the double quotes (and left the single quotes) around the batch file name:
C:\Windows\system32>echo ['D:\to ols\echo-cd.bat' foo]
['D:\to ols\echo-cd.bat' foo]
C:\Windows\system32>if ['D:\to] == [] (goto :help ) else (goto :checkPrivileges )
I recall using the following approach for this:
start "" %systemroot%\System32\windowspowerShell\v1.0\powershell.exe -exec bypass -noprofile -command "&{ start-process powershell -verb RunAs -ArgumentList '-noprofile -exec bypass -file \"c:\temp\test folder\elevatedpowershell.ps1\"'}"
You can replace \"c:\temp\test folder\elevatedpowershell.ps1\" with \"$0\" like you did there.
I also found the solution from Keith Hill on self elevating PowerShell to be useful if I need the person to be admin. I do not have the link now but it goes like this:
function IsAdministrator
{
$Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
$Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
function IsUacEnabled
{
(Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}
if (!(IsAdministrator))
{
if (IsUacEnabled)
{
[string[]]$argList = #('-NoProfile', '-File', ('"' + $MyInvocation.MyCommand.Path + '"'))
$argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
$argList += $MyInvocation.UnboundArguments
Start-Process "$env:Windir\System32\WindowsPowerShell\v1.0\PowerShell.exe" -Verb Runas -WorkingDirectory $pwd -WindowStyle Hidden -ArgumentList $argList
return
}
else
{
throw "You must be administrator to run this script"
}
}
Assuming, you want to have elevated PowerShell script, you can have that at the top of your PowerShell script.
Ugly but it can do the job.
Use single quotes (or any character of your choice) and insert this in your code:
:gotPrivileges
cd "%~p0"
set arg=%*
set arg=%arg:'="%
%arg%
:: %*
pause
If you have 8.3 file names enabled you can try this:
:getPrivileges
setlocal enabledelayedexpansion
set Args=%*
for %%a in (%*) do if exist %%a (
set Args=!Args:%%a="%%~sa"!
)
PowerShell "Start-Process -FilePath \"%0\" -Verb RunAs -ArgumentList \"%Args%\"" 2>nul
goto :exit
However, if you pass an argument that happens to be the name of a file or folder (that exists relative to RunElevated.bat) it can get altered.

Resources