Skip to content

Instantly share code, notes, and snippets.

@LuczynskiDar
Last active March 15, 2021 15:45
Show Gist options
  • Save LuczynskiDar/c4e52770be72e72c1d346e72d22a3db3 to your computer and use it in GitHub Desktop.
Save LuczynskiDar/c4e52770be72e72c1d346e72d22a3db3 to your computer and use it in GitHub Desktop.

Login into the powershell console

Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds" -Name ConsolePrompting -Value $true
Get-ComputerInfo | select WindowsProductName, WindowsVersion

Msiexec - silent installations

$DataStamp = get-date -Format yyyyMMddTHHmmss
$logFile = '{0}-{1}.log' -f $file.fullname,$DataStamp
$MSIArguments = @(
    "/i"
    ('"{0}"' -f $file.fullname)
    "/qn"
    "/norestart"
    "/L*v"
    $logFile
)
Start-Process "msiexec.exe" -ArgumentList $MSIArguments -Wait -NoNewWindow

Command options https://docs.microsoft.com/en-us/windows/win32/msi/command-line-options https://docs.microsoft.com/en-us/windows/win32/msi/standard-installer-command-line-options

/quiet, /q, qn	#Fully silent mode
/passive	#Unattended mode, shows progress bar only.
/norestart	#Do not restart the system after the installation
/forcerestart	#Restart the system after installation is complete
/log, /l	#Enable Logging

Silently install the msi package:

msiexec /i C:\setup.msi /qn

Silently install the msi package, no reboot

msiexec /i C:\setup.msi /qn /norestart

Silently install the msi package and write the installation log to file C:\msilog.txt

msiexec /i C:\setup.msi /l*v C:\msilog.txt /qn

Silently uninstall the msi package:

msiexec /x C:\setup.msi /qn

Silently uninstall the msi package by the product code:

msiexec /x {XXXXXXXX-9215-4780-AAC6-01FD101DC931} /qn

A software package previously installed from an msi file can be uninstalled with this command:

MsiExec /x package.msi

The most commonly used option is the one which allows to do unattended deployments, by supressing all requests for user input. It makes the installer use the defaults instead of asking any questions:

/qb

This option comes in a variant which additionally also disables the abort button in the message window, which shows the progress:

/qb!

There is related option which appears to be useful, that not only suppresses all questions, but also all output. However you should better not use it, because some software does not deploy correctly when installed with this option:

/qn

If an install or update does not work, it can be useful to let MsiExec write a log file. That usually contains hints why it did not work (hidden in the middle of thousands of irrelevant lines):

/L*v c:\MsiExec-output.txt

Filenames which contain spaces must be enclosed in double quotes. Examples:

MsiExec /qb /i "great app.msi" /update "c:\path\new patch.msp"
MsiExec /qb /i app.msi TRANSFORMS="default.mst;my defs.mst"

Get apssword from credetials

$cred = Get-Credential COMPANY\DJones $cred | get-member Get-WmiObject -class Win32_BIOS -Computer SERVER1 -Credential $cred

cd WSMan:\localhost\Service Set-Item AllowUnencrypted $True cd .\Auth Set-Item Basic $True

$PSVersionTable

Set-WSManQuickConfig -force

get-WSManCredSSP Enable-WSManCredSSP -Role Client -DelegateComputer {domain-name} Enable-WSManCredSSP -Role Server

Display a list of stored user names and credentials: cmdkey /list

Add a generic TERMSRV credential for user PeteZ (on domain dom64) to access the computer Server64: cmdkey /generic:TERMSRV/Server64 /user:dom64\PeteZ /pass:p4g67hjyy23

Delete the stored TERMSRV credential for Server64: cmdkey /delete TERMSRV/Server64

Add a user name and password for user Kate to access computer Server64 with the password z5rd63hGtjH7: cmdkey /add:server64 /user:Kate /pass:z5rd63hGtjH7

Add a user name for user Kate to access computer Server64 and prompt for a password whenever Server64 is accessed: cmdkey /add:server64 /user:Kate

Delete the stored credential for Server64: cmdkey /delete:Server64

Using CredentialManager

$mc_creds = (Get-StoredCredential -AsCredentialObject) | Where-Object {$_.TargetName -like "*term*" -and $_.TargetName -like "*xxxx*"}

Winrm and network connection profile

Running the following command in Powershell starts the RDP session exactly as I would expect: cmdkey /generic:TERMSRV/localhost /user:username /pass:password; mstsc /v:localhost

Target: LegacyGeneric:target=TERMSRV/localhost Type: Generic User: username

PowerShellInstance.AddParameter("; mstsc /v:localhost")

cmdkey /generic:TERMSRV/ /user: /pass:

cmdkey /generic:$Server /user:$User /pass:$SecurePassword mstsc /v:$Server /h:1080 /w:1920

net use \10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes

c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nolog -command cmdkey /generic:TERMSRC/some_unc_path /user:username /pass:pa$$word; mstsc /v:some_unc_path

Even when you have the "Clipboard" option enabled, you may still have problems! If that's the case, use Task Manager to kill and restart the rdpclip.exe process on local and remote machines. https://superuser.com/questions/95609/cant-copy-and-paste-in-remote-desktop-connection-session

+--------------------------+-------------------------+------------------------------+
| Symptom                  | Possible Cause          | Possible Solution            |
+--------------------------+-------------------------+------------------------------+
| Remote-to-local copy and | RDPCLIP is not in the   | Kill and restart RDPCLIP.    |
| paste broken.            | clipboard viewer chain. |                              |
+--------------------------+-------------------------+------------------------------+
| Local-to-remote copy and | TS client is not in the | Close the TS client and      |
| paste broken.            | clipboard viewer chain. | reconnect to the session.    |
+--------------------------+-------------------------+------------------------------+
| RDPCLIP or the TS client | There is a loop in the  | Kill and restart RDPCLIP.    |
| is using excessive CPU.  | local or remote         | If this does not fix the     |
|                          | clipboard viewer chain. | problem, close the TS client |
|                          |                         | and reconnect to the session.|
+--------------------------+-------------------------+------------------------------+

Workaround

Enable-PSRemoting -SkipNetworkProfileCheck
  1. Windows 8.1 and above
Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private
  1. Windows 7
$networkListManager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}")) 
$connections = $networkListManager.GetNetworkConnections() 

# Set network location to Private for all networks 
$connections | % {$_.GetNetwork().SetCategory(1)}

Windows Remote Management Command Line Tool

Windows Remote Management (WinRM) is the Microsoft implementation of the WS-Management protocol which provides a secure way to communicate with local and remote computers using web services.

$session = New-PSSession -ComputerName localhost -ConfigurationName MyNonAdmin -Credential $adminCred


Find-Credential | Where Target -like "*term*"
Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI -FORCE

Set-Item WSMan:\localhost\Client\TrustedHosts * -Force
winrm quickconfig
winrm get winrm/config
winrm g winrm/config/client
Get-Service winrm | ft -AutoSize
winrm get winrm/config/listener?Address=*+Transport=HTTP

Get-PSSessionConfiguration
Get-PSSessionConfiguration microsoft.powershell | fl *
remove-pssession -session (get-pssession)
Enter-PSSession -ComputerName xxxx -Credential $mc_creds

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell
#WARNING: Set-PSSessionConfiguration may need to restart the WinRM service if a configuration using this name has recently been
#unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required.
#All WinRM sessions connected to Windows PowerShell session configurations, such as Microsoft.PowerShell and session configurations
#that are created with the Register-PSSessionConfiguration cmdlet, are disconnected.

# permissions for http://schemas.microsoft.com/powershell/microsoft.powershell

Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI -FORCE
$Password = $Credentials.GetNetworkCredential().Password

### and other info
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password

First we get a reference to a COM instance of an INetworkListManager which naturally has a Class ID of DCB00C01-570F-4A9B-8D69-199FDBA5723B. We then grab all the network connections and finally set them all to the desired location:

0 - Public 1 - Private 2 - Domain

Reference: http://www.hurryupandwait.io/blog/fixing-winrm-firewall-exception-rule-not-working-when-internet-connection-type-is-set-to-public

Create new credentials

$username = domain\username
$password = cat C:\test\password.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

Exporting credentials

 $outfile = "c:\filelocation.xml"
 Get-Credential | export-clixml -path $OutFile

Import credentials

 $Creds = Import-Clixml -Path "c:\file.xml"

Start process

runas

runas /noprofile /user:%COMPUTERNAME%\myaccount "powershell.exe -NoProfile -ExecutionPolicy ByPass -file %~dp0testscript.ps1"

Start-Process

I always recommend to add the parameters -Noprofile and -ExecutionPolicy Bypass when using Powershell.exe to launch scripts or execute commands, just to make sure it works despite of the Execution Policy set or any present user or machine profile scripts. However, at least the parameter -NoProfile seems not to work the same when Powershell.exe is being called fom the above CMD or PS1. Called from PS1, my machine profile gets nevertheless executed, but not fom CMD... interesting

$Username       = "$($env:COMPUTERNAME)\myaccount"
$Password       = 'mypassword'
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$ScriptFile     = Join-Path -Path $PSScriptRoot -ChildPath 'testscript.ps1'
$Credential     = New-Object System.Management.Automation.PSCredential( $Username, $SecurePassword)
$StartOpts = @{ 'FilePath'        = 'powershell.exe'
                'Credential'      = $Credential
                'NoNewWindow'     = $false
                'ArgumentList'    = @( '-f', $ScriptFile,
                                       '-ExecutionPolicy', 'Bypass',
                                       '-NoProfile'
                                     )
               }
Start-Process @StartOpts

$username = "username" 
$password = "password"
$startWithElevatedRights = "notepad"

$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ',  $startWithElevatedRights, ' -Wait -verb runas}'

$ps.WaitForExit()

Example2

$args = "-NoProfile -ExecutionPolicy Bypass -File c:\test\test.ps1"
Start-Process Powershell -Credential $cred -ArgumentList $args
"$currentUser called script as HS0\cuser2"  | Out-File 'c:\test\test.log' -Append

Example3

Start-Process powershell.exe  -Credential $Credential -NoNewWindow -ArgumentList "(Start-Process -FilePath '\\some\path\app.exe' -ArgumentList  '/q).ExitCode"

Example4

Start-Process -NoNewWindow -Wait "$env:ProgramFiles\$OpenSSH_Win64_folder\ssh-keygen.exe"

Example5

Install-Module -Name CredentialManager

Invoke-Command

Invoke-Command -ComputerName $env:COMPUTERNAME -Credential $credential -ArgumentList $Arguments -ScriptBlock

bat file

PowerShell -NoProfile -ExecutionPolicy Bypass -File "c:\test\test-switch.ps1"

Initializing and working withthe PasswordVault Object

# Assemblies
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]

#Initializing the PasswordVault Object

$vault = New-Object Windows.Security.Credentials.PasswordVault
$vault.RetrieveAll()

#Add credential

$cred = New-Object windows.Security.Credentials.PasswordCredential
$cred.Resource = 'My Credentials'
$cred.UserName = 'MyDomain\MyUserName'
$cred.Password = 'MyPassword'
$vault.Add($cred)
Remove-Variable cred # So that we don't have the password lingering in memory!

#Now let’s pluck out the specific credential we want.

$StoredCredential = $creds.where({$_.Resource -eq "My Other Credentials"})
$StoredCredential.RetrievePassword()
$StoredCredential.Password

A slightly different syntax for doing the above can be seen here.  Note that the Select-Object cmdlets are included to address the off chance of multiple matches for a particular Resource.

[string]$userName = ($vault.RetrieveAll() | Where-Object {$_.Resource -eq "My Other Credentials"} | Select-Object -First 1).UserName
[string]$userPass = ($vault.Retrieve("My Other Credentials",$userName) | Select-Object -First 1).Password

[SecureString]$securePass = ConvertTo-SecureString -String $userPass -AsPlainText -Force

Invoke creds

Invoke-Command -ComputerName COMPUTER -ScriptBlock { COMMAND } -credential USERNAME Invoke-Command -ComputerName 192.168.122.66 -Credential Administrator -ScriptBlock {Get-Culture}

Test-WsMan COMPUTER

$job = Start-Job -scriptblock { param ($username) some code to run against the variable that was passed in } -Args $target -credential $Cred

You can also use -ScriptBlock instead of -FilePath if you have a simple chunk of code to run or you have converted a script to a script block

param ([string]$username,[string]$password)

Script contents: $Username = '[email protected]' $Password = ConvertTo-SecureString -String $password -AsPlainText -Force $Credential = New-Object -Type PSCredential($Username,$Password) $Session = New-PSSession -Credential $Credential

Invoke-Command -Session $Session -FilePath C:\Path\to\some\script.ps1

$account= # AD account $password = # AD user password $passwordSecure = ConvertTo-SecureString ($password) -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential ($account, $passwordSecure)

$ScriptBlock = { whoami start-sleep 3 }

Run PowerShell as Administrator with Custom Crednetails

start-Process powershell.exe -Credential $Cred -ArgumentList "-Command Start-Process powershell.exe -Verb Runas -ArgumentList '-Command $ScriptBlock'" -Wait

Get the other user's credentials

$credential = Get-Credential

Execute a scriptblock as another user

$commands = @' $env:username # ... more commands ... '@ Start-Process -FilePath Powershell -LoadUserProfile -Credential $credential -ArgumentList '-Command', $commands

Execute a file as another user

$script = '.\path\name.ps1' Start-Process -FilePath Powershell -LoadUserProfile -Credential $credential -ArgumentList '-File', $script

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7

Invoke-Command -ComputerName 10.0.0.22 -ScriptBlock { Get-ChildItem C:\ } -credential wjgle

$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd

Set up credentials.

$password = ConvertTo-SecureString -String $env:Password -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential $env:Username,$password

Invoke-Command -ComputerName RemoteServerName -Credential $cred -ScriptBlock { get-childitem \path\to\another\remove\server\within\the\same\domain }

ACL management

(get-acl .\ssh_host_dsa_key).owner

The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation

Open Registry Editor on the affected machine (regedit.exe) Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Protect\Providers\df9d8cd0-1501-11d1-8c7a-00c04fc297eb (this last part is the same for all machines) Create a new 32bit DWORD, named "ProtectionPolicy" Double click the key again and set a value of "1" Restart the affected computer Run Bootstrap again, this time no errors should arise and certificates should be recreated correctly

Secure string

$Secure_String_Pwd = ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force $Secure_String_Pwd | ConvertFrom-SecureString | Out-File "somefi.txt" cat .\somefi.txt 01000000d08c9ddf0115d1118c7a00c04fc297eb01000000cbeb2297f38a2a4294e630c7e7572f410000000002000000000003660000c000000010000000484893f6930acaef1d02ae3fdebb9bca0000000004800000a0000000100000001120e62c54e57d1fd409c1944474163418000000f15658fe3fbedc0118cb97f2e5234912b60a5e9c314eadf714000000d92bdcd905adf63aa64ce5eded5425830f1a7408

Exwcution policy

The acceptable execution policy values are as follows:

  • AllSigned. Requires that all scripts and configuration files are signed by a trusted publisher, including scripts written on the local computer.
  • Bypass. Nothing is blocked and there are no warnings or prompts.
  • Default. Sets the default execution policy. Restricted for Windows clients or RemoteSigned for Windows servers.
  • RemoteSigned. Requires that all scripts and configuration files downloaded from the Internet are signed by a trusted publisher. The default execution policy for Windows server computers.
  • Restricted. Doesn't load configuration files or run scripts. The default execution policy Windows client computers.
  • Undefined. No execution policy is set for the scope. Removes an assigned execution policy from a scope that is not set by a Group Policy. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted.
  • Unrestricted. Beginning in PowerShell 6.0, this is the default execution policy for non-Windows computers and can't be changed. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you're prompted for permission before it runs.

The effective execution policy is determined by the order of precedence as follows:

  • MachinePolicy. Set by a Group Policy for all users of the computer.
  • UserPolicy. Set by a Group Policy for the current user of the computer.
  • Process. Affects only the current PowerShell session.
  • CurrentUser. Affects only the current user.
  • LocalMachine. Default scope that affects all users of the computer.
Get-ExecutionPolicy -List
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine
Unblock-File -Path .\Start-ActivityTracker.ps1
Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope Process
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-ExecutionPolicy } | Set-ExecutionPolicy

Netsh

netsh wlan show profiles netsh wlan show profile name=xxxx key=clear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment