Delete Credential Manager Stored Credentials at once - cmd

I was looking for a more efficient way to delete all credentials stored in Credential Manager without having to delete credentials one by one. After few hours of browsing, I have finally stumbled upon this command prompt string that does exactly what I need:
for /F "tokens=1,2 delims= " %G in ('cmdkey /list ^| findstr Target') do cmdkey /delete %H
Since my knowledge of this syntax is quite limited, I would like to know what each of its section actually means. I already know what cmdkey /list, findstr and cmdkey /delete do but I am not sure about the rest.
Moreover, I would like to know how to make exceptions. For instance, in this case the line deletes all the strings that have a target as displayed in cmdkey list:
cmdkey.exe /list example
What if I want to make an exception and delete only some credentials but not other? Could I do that using the Type value instead of the Target value, for instance by asking the command prompt to delete only the Generic type credentials and not the Generic Certificate and the Domain Password type credentials?
Thanks in advance for your help.
KR,
Andy

When using the string "for /F "tokens=1,2 delims= " %G in ('cmdkey /list ^| findstr Target') do cmdkey /delete %H", I keep getting "CMDKEY: Element not found."
Therefore I scripted a quite primitive workaround since I do not know batch syntax so well. The script below puts together all the lines that have to be run in cmd to delete the corresponding CM keys. The last command in the script, invokes the file with all the lines. You have to just copy/paste them in a cmd and hit enter and it removes most of them:
$cachedCredentials = cmdkey /list
$CMCredentialsTxt = "C:\temp\CMCredentials.txt"
$cachedCredentials | Out-File $CMCredentialsTxt
(Get-Content $CMCredentialsTxt) | ? {$_.trim() -ne "" } | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Trim() | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("Currently stored credentials:","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("Type: Generic", "") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("User: App Info","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("Local machine persistence","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("Target: ","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("User: <Certificate>","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("Certificate","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("User: User DT","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt).Replace("User: User OS Info","") | Set-Content $CMCredentialsTxt
(Get-Content $CMCredentialsTxt) | ? {$_.trim() -ne "" } | Set-Content $CMCredentialsTxt
$cleanTargets = Get-Content $CMCredentialsTxt
Remove-Item $CMCredentialsTxt
forEach ($cleanTarget in $cleanTargets){"cmdkey /delete:" + $cleanTarget | Out-File $CMCredentialsTxt -Append}
Invoke-Item $CMCredentialsTxt

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

How do we implement %* in powershell? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When I try to execute %* inside batch script by using powershell, it gives me an error. I need something to be replaced for %* so that it works for the following code snippet:
%* ^| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^| Out-File -FilePath $filepath -Append -NoClobber}
First, know why this is not valid code:
%* $| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^| Out-File -FilePath $filepath -Append -NoClobber}
Get-Alias -Definition ForEach-Object |
Format-Table -AutoSize
# Results
<#
CommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
Alias foreach -> ForEach-Object
#>
This is why you get...
%*
%*: The term '%*' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
... when you use it.
And this ...
^
... is a termination character
Second, as well as your code is not a one-liner, as I commented above. What you really have is this...
ForEach-Object '*' ^|
ForEach-Object {
Write-Host $PSItem
$filepath = 'loggerfile.log'
$output_file = $(Get-Date).ToString() + ' ' + $PSItem
Write-Output $output_file ^|
Out-File -FilePath $filepath -Append -NoClobber
}
... and this.
ForEach-Object '*' ^
is not valid at all. I am curious as to where you got that from. As well as this...
^|
... as that is not a thing I've ever seen in any PowerShell docs, help files, repo code. This is also not aliases for anything natively.
Did you mean to do this...
$^
which means - The first token of the last command. Note though, it 'Does NOT' refer to the whole command.
The | pipe is of course pass results from the left of it to the right of it. What are you expecting this...
ForEach-Object '*' ^|
...to do? Even if you did, that is not valid and would error off with.
ForEach-Object: You cannot call a method on a null-valued expression.
So, did you mean to do this...
%* $^
... which is still something I've never seen in 10+ years I've been messing with Monad/Windows PowerShell/PowerShell Core.
To know what your code is doing, you take two steps.
Use PSSCriptANalyzer to validate what you are doing according to the PowerShell ruleset
Invoke-ScriptAnalyzer "$PWD\SomeScriptName.ps1"
Trace the execution, so you can see the stack.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/trace-command?view=powershell-7.1
Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {
%* ^| ForEach-Object { Write-Host $_ ; $filepath = 'loggerfile.log' ; $output_file =$(Get-Date).ToString() + ' ' + $_ ; Write-Output $output_file ^| Out-File -FilePath $filepath -Append -NoClobber}
} -PSHost

Getting List of Installed Applications that Matches Add/Remove Programs List

I'm working on an application that lists all of the installed programs on a customer's computer. I've been able to get a list based on registry keys, but it doesn't include things that were installed via the Microsoft Store. It looks like using PowerShell (based on the guidance on this page: https://mhelp.pro/how-to-uninstall-windows-apps/) I can get lists of installed applications, but what I'm getting there seems to include a lot of items that aren't in Add/Remove Programs, and I'm not sure how to reconcile the 2 sources (Add/Remove Programs and the lists of programs via PowerShell). Is there some better way I should be doing this, or is there a flag or criteria that I should be using to determine if a listed application is present in Add/Remove Programs?
Perhaps something like that did you mean ?
Refer to How to Create a List of Your Installed Programs on Windows
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize |
Out-File $outputFile -Encoding UTF8 -Force
Start-Process $outputFile
EDIT : 25/08/2020 # 18:20
Here is a Self-elevate script to get everything with admin rights :
cls
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
#$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
$CommandLine = $MyInvocation.InvocationName
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
$outputFile = "$env:APPDATA\Installed_Applications.txt"
$OS_Architecture = $env:PROCESSOR_ARCHITECTURE
if($OS_Architecture -eq 'x86')
{
#write-host '32-bit'
$key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
else
{
#write-host '64-bit'
$key = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
}
Get-ItemProperty $Key |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize | Out-String -Width 300 |
Out-File $outputFile -Encoding UTF8 -Force
Get-AppxPackage -AllUsers |
Out-File -Append $outputFile -Encoding UTF8 -Force
Start $outputFile
In powershell 5 but not powershell 7:
get-package

dos2unix format conversion error while execution through TeamCity

While trying to transfer file from Windows to Unix Azure environment, I am getting error dos2unix format error
dos2unix -o /xyz/home/ABC_efg.txt failed to execute dos2unix format change.
I tried to run a PS script to fix it but does seem to work .
Get-ChildItem -File -Recurse *.txt | % { $x = get-content -raw -path $_.fullname; $x -replace "`r`n","`n" | set-content -NoNewline -path $_.fullname }
Instead of using -replace, I would prefer to read the content(s) as string array and join these strings with "`n".
Something like this:
$files = Get-ChildItem -File -Recurse -Filter '*.txt' | Select-Object -ExpandProperty FullName
$files | ForEach-Object {
(Get-Content -Path $_) -join "`n" | Set-Content -Path $_ -NoNewline -WhatIf
}
Remove the -WhatIf switch if you are satisfied with the outout shown in the console.
Well, part of the issue is that you are piping a string to Set-Content and then trying to use that string to determine where to save the file. Try changing the last part from:
$x -replace "`r`n","`n" | set-content -NoNewline -path $_.fullname
to this:
set-content -NoNewline -path $_.fullname -value ($x -replace "`r`n","`n")
If that doesn't update the formatting like you expect it to you may need to use the -Encoding parameter for Set-Content. I'm not real familiar with encoding though, so I am not sure about that.

Batch file: Combine echos into one line

I want to dump all the file names in a folder without extension into a text file. They should be in one line separated by commas.
So in my folder I have
File1.bin
File2.bin
....
With
(for %%a in (.\*.bin) do #echo %%~na,) >Dump.txt
I got
File1,
File2,
But what I want in the end is a text file with, so one long combined string.
File1,File2,...
I'm kinda stuck here and probably need something else than echo.
Thanks for trying to help.
Try like this:
#echo off
setlocal enableDelayedExpansion
for %%a in (.\*.txt) do (
<nul set /p=%%~nxa,
)
check also the accepted answer here and the dbenham's one.
You could also leverage powershell from a batch-file for this task:
#"%__APPDIR__%WindowsPowerShell\v1.0\powershell.exe" -NoProfile -Command "( Get-Item -Path '.\*' -Filter '*.bin' | Where-Object { -Not $_.PSIsContainer } | Select-Object -ExpandProperty BaseName ) -Join ',' | Out-File -FilePath '.\dump.txt'"
This could probably be shortened, if necessary, to:
#PowerShell -NoP "(GI .\*.bin|?{!$_.PSIsContainer}|Select -Exp BaseName) -Join ','>.\dump.txt"

Resources