PowerShell Commands
|
AD and PowerShell
Automate Active Directory with PowerShell Tutorial 1 : Introduction
|
Get-ADUser -Identity charles.beaver -server
"SERVER2022DC" -Properties * - get all the properties, of an AD user
from the AD server. |
Set-ADUser
NewADUser
Remove-ADUser |
Start a Remote PS Session with my DC
|
$cred=Get-Credential
$sess = New-PSSession -Credential $cred -ComputerName
SERVER2022DC
Enter-PSSession $sess
Enable-PSRemoting -Force
go into the WSMAN config on the Target server and set the relevant
settings
for allowing Basic Auth and an unencrypted connection:
cd WSMan:\localhost\Service
Set-Item AllowUnencrypted $True
cd .\Auth
Set-Item Basic $True
Exit-PSSession |
Remove-PSSession $sess
$s=New-PSSession -computerName SERVER2022DC
winrm set winrm/config/client '@{TrustedHosts="SERVER2022DC,
2019SERVER, WINSRVR2019-2, DESKTOP-94OBPF2"}'
Get-Item -Path wsman:\localhost\Client\TrustedHosts
(Get-PSSessionConfiguration -Name
Microsoft.PowerShell).Permission
NT AUTHORITY\INTERACTIVE AccessAllowed,
BUILTIN\Administrators AccessAllowed, BUILTIN\Remote
Management Users AccessAllowed
Restart-Service WinRM -force
Test-WsMan SERVER2022DC |
Prerequisites for Remoting That Need to Be
In Place
|
WinRM Service: This service receives
requests from other computers and needs to be
running.
Listener: Inside WinRM, a listener needs to be set
up that listens on the network port Windows
PowerShell Remoting uses to communicate.
Firewall Exception: A firewall exception is needed
that allows outside requests to reach the WinRM
service.
Enable-PSRemoting - sets up the above prerequisites
Set-Item wsman:\localhost\client\trustedhosts *
-Force - configures Windows PowerShell Remoting so
that you can connect to any computer, not just those
inside your own trusted domain(s).
Invoke-Command { Get-Service } -ComputerName
SERVER2022DC
Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName
SERVER2022DC - The script runs on the remote
computer and the results are returned to the local
computer
Invoke-Command -ComputerName SERVER2022DC
-Credential Domain_Name\Administrator -ScriptBlock {
Get-Culture } -
runs a Get-Culture command on the SERVER2022DC
remote computer.
Invoke-Command -ComputerName SERVER2022DC
-Credential Domain_Name\Administrator -ScriptBlock
{Get-Culture}
Windows Remoting has to be turned on:
Computer Configuration/Policies/Administrative
Templates/Windows Components/Windows Remote
Management |
How to Create a PowerShell Session on a
Remote Computer
|
How to Create a PowerShell Session on a Remote
Computer |
about_Remote_Requirements |
Enable-PSRemoting - enable a remote PS session
Enable-PSRemoting -Force - same as above; use -force
when above doesn't work
winrm set winrm/config/client '@{TrustedHosts=""}' -
insert an * if u want all servers; not safe
winrm set winrm/config/client
'@{TrustedHosts="SERVER2022DC, 2019SERVER,
WINSRVR2019-2"}' - same as above; gives the server
(winrm) which specific (other) servers are to be
trusted to do remote sessions on this remote server
Restart-Service WinRM -force - reboot the WinRM
service
Test-WsMan <RemoteCOMPUTERName> - test the WinRM
service on the remote server; does it exist?; is it
available?
Test-WsMan SERVER2022DC --------- same as above with
the server name inserted
$cred=Get-Credential - creates a variable called $cred
and inserts the Get-Credential command into that
variable.
$sess = New-PSSession -Credential $cred -ComputerName
<remotemachinename>
$sess = New-PSSession -Credential $cred -ComputerName
SERVER2022DC - uses the Get-Credential command,
inside the variable, and runs a new PS session. This
creates the remote session, on the remote computer,
without getting into (starting) it.
Enter-PSSession $sess - using the variable created,
and the switches added in the second command, start
the remote PS session.
<Run commands in remote session>
Exit-PSSession - end the remote PS session
Remove-PSSession $sess - removes the PS session
(waiting in the background) on the local
computer/server.
To configure PowerShell to receive remote commands:
Start PowerShell with the Run as administrator
option.
At the command prompt, type: Enable-PSRemoting |
Other Commands
|
"?" stands for Where-Object and "%"
stands for ForEach-Object.
cntrl spacebar ------- gives options
for completing a command
dir variable:/ -------- display all of the available variables
get-variable Host | gm - get this variable (called Host) and display its
details (gv for
short)
Enter-PSSession ---- connects to an interactive session x
Get-PSSession ------ lists all sessions
New-PSSession ----- creates a new session x
Remove-PSSession - closes and discards a session
Test-WSMan -------- connects to wsman x
Clear-EventLog ----- clears all event log entries
gal - get aliases
gal g* get aliases that start with g (most are get aliases)
Get-Counter --------- gets performance counter data
Get-EventLog -------- gets event logs and event log entries
get-module - to see the loaded modules
get-module -listavailable - show available modules
get-module -Module <module> - to list commands in a module
(get-module <module name>).Version - shows which module version that you
have.
Get-HotFix ----------- gets hotfixes and updates x
Get-Process --------- gets running processes
Get-Service ---------- gets services
Get-WmiObject ------ gets instances of WMI classes x
Invoke-WmiMethod - calls WMI methods x
Invoke-Command --- executes code in a session x
Limit-EventLog ------- limits the size of event logs
New-EventLog ------- creates a new event log and/or an event source
Register-WmiEvent -- subscribes to WMI events x
Remove-EventLog --- deletes an event log and/or event sources
Remove-WmiObject - deletes an instance of a WMI class x
Restart-Computer --- restarts the operating system x
Set-Service ---------- changes the settings of a service
|
[array]$Global:Results = #() -
creates an array
Show-EventLog ------ opens the event log in the
Event Viewer window
Stop-Computer ------ shuts down a computer x
Set-WmiInstance ---- creates or updates an instance
of a WMI class x
cntrl ` ---------------- opens the powershell
terminal at the bottom of VSCode
<# #> anything within this construct are all
comments
$psversiontable - which version of PS do I have? -
works in Core but not regular PS.
get-alias ---- shows a list of all of the aliases
get-alias cd - what is the name of the actual PS
command behind the change directory (cd) alias?
- the return will be set-location
get-alias dir - what is the name of the actual PS
command behind the directory (dir) alias?
- the return will be Get-ChildItem
get-alias -definition get-process - what are the
alias's for the get-process command
get-childitem | select -Property name, length | sort
-Property length -Descending - get the child item
get-childitem .\some_folder_name\ - will display the
contents of this folder
get-item .\some_folder_name\ - will display only the
folder name and not its contents
Get-PSDrive - lists all of the drives, and the
registry and variable, wsman, etc.
cd env: ------ change to the environment
ls ------------ (done in env) this shows all of the
environment variables
cd HKCU: ---- lets you edit that key in the registry
install-module az ------------ install the az module
import-module az.compute - import the az.compute
module
update-module az ----------- update the az module
update-help ------------------ update the help
feature
get-help get-process -online - open the web site
with the get-process information on it.
get-command ----------------- show all commands |
Find-Module -Tag Telegram - find a (powershell) module that does
something with the Telegram application.
Get-ADComputer -filter * |get-wmiobject win32_bios -ComputerName
{$_.name}
Get-ADComputer -filter * | gm - find out what the property object is for
this command; it's ADComputer
Get-ADComputer -filter * |get-wmiobject -class win32_bios - this isn't
going to work. However, do the following and figure it out.
get-adcomputer -filter * | gm - it shows the details of get-adcomputer -
take another step in making the above work with the following
Get-ADComputer -filter * | Select -ExpandProperty name - show the
computer names
Get-ADComputer -filter * | Select -ExpandProperty name | gm - pipe the
above command to get member. You'll notice that this object, shown in
the return (data) is a string object; which is what we need to execute
the 1st statement in this section.
Get-ADComputer -filter * | Select -ExpandProperty name
Get-ADComputer -filter * | Select -Property name - this will give you
all of the names of your computers.
Get-ADComputer -filter * | Select -Property name, @{name='ComputerName'
;expression={$_.name}} - creates a ComputerName property
Get-ADComputer -filter * | Select -Property name, @{n='ComputerName'
;e={$_.name}} - same as above
Get-ADComputer -filter * | Select -Property @{n='ComputerName'
;e={$_.name}} - same as above; now that you've created the ComputerName
property
Get-ADComputer -filter * | get-service -name bits
Get-ADComputer -filter * | gm - what type of object am I working with?
- the return will show that this is an ADComputer object
get-command -noun process -- show all Cmdlets related to a process; like
debug, get, start, stop & wait(-process)
Get-Command | Where-Object { $_.Parameters.Keys -contains 'ComputerName'
-and $_.Parameters.Keys -notcontains 'Session'}
- to identify only those (cmdlets) that use classic remoting techniques,
exclude cmdlets with a Session parameter.
Get-Command -CommandType cmdlet | ? { @($_.ParameterSets | ? { $p =
$_.Parameters | Select-Object -Expand Name;
(($p -contains 'computername') -and ($p -contains 'credential'))}).Count
-gt 0} - find all cmdlets that support
both the ComputerName and the Credential parameters in one parameter set
get-content .\procs.txt - show, to the screen the details inside the
file called procs.txt
get-eventlog - doesn't normally run in core but can run if you have a
compatibility module installed
get-eventlog -LogName System -Newest 3 -EntryType error - show the 3
most recent errors in the system event logs
get-eventlog -LogName System -Newest 3 -EntryType error -ComputerName
dc,s1,s2 - show the above from these 3 computers
get-eventlog -LogName System -Newest 5 | Select -Property EventId,
TimeWritten, Message | sort -Property timewritten
- show the 5 newest system eventlog entries with only the EventId,
TimeWritten and Message attributes and sort by timewritten
get-eventlog -LogName System -Newest 5 | Select -Property EventId,
TimeWritten, Message | sort -Property timewritten
| ConvertTo-html | out-file c:\error.htm - same as above but pipe it
to an html file called error.htm
get-eventlog -LogName system -new 3 - will pull the most recent 3 log
entries from a server
Get-EventLog Application -EntryType Error -ComputerName SERVER2022DC
Get-EventLog System -after (get-date).AddMinutes(-1000) - get the events
for the last 1000 minutes.
Get-ExecutionPolicy
get-help Get-CimInstance
get-help get-service -detailed ------- the verbose version of help
relating to get-service
get-help get-service -full ------------- the maximum local help details
get-help get-service -online ---------- the online version of help -
which is, by far, the best of all
get-help get-service -ShowWindow - displays help in a separate window
(with excellent formatting)
get-help *eventlog* ------------------ show all commands that have any
reference to Event Logs.
get-help get-eventlog -detailed ------ show the verbose details for the
command get-eventlog
get-help Get-wmiobject -full - if you scan through the output, of this
command, you will see many things with the word false beside them. It's
telling you that these don't
take pipeline imput. We're still trying to ge the 1st command above to
work.
get-help Get-wmiobject - notice, from the output, of this command, that
[-ComputerName <string[]>] this is telling you that the ComputerName
parameter wants a string
for input.
get-help * -Parameter ComputerName - identify cmdlets with built-in
remoting support
get-help *service* - find all commands with service in the name
get-help *pswa* - show all of the modules available for (or needed for)
Power Shell Web Access
get-help get-service -showwindow - look at the details of the
get-service object. Do a search for ByValue.
- then do a search for ByPropertyName.
GET-HELP -Category ASDFGH - the output will show all of the possible
help categories; like "Alias, Cmdlet, Provider,
General,FAQ,Glossary,HelpFile,ScriptCommand,Function,Filter,ExternalScript,All,DefaultHelp,Workflow,DscResource,
Class and Configuration"
Get-Module -ListAvailable ------ shows a list of all of the available
modules.
Get-Module --------------------- shows the currently loaded modules.
Get-NetIPInterface | Format-List - shows the identifier of the NIC that
you are using.
get-process ------------------------------------------ show all of the
running processes
get-process |where handles -gt 900 ---------------- show all of the
processes where the handles are greater than 900
get-process |where handles -gt 900 |sort handles - same as above but
sort by the handles
get-process | Export-clixml -Path c:\good.xml ----- export all processes
to an XML file called good.xml
get-process | gm ------------------------------------- show the
processes and give all of the properties of these processes.
get-process a* ----------------- show all the running processes that
start with the letter a.
get-process a* | get-member - show the properties, methods, and other
details, regarding these processes that start with the letter a
get-process | where-object{$_.name -eq "notepad"} - show the details of
all running notepad processes
get-process | where-object{$_.name -eq "notepad"} | stop-process - stop
all notepad processes that are running
(get-process | where-object{$_.name -eq "notepad"}).kill - creates a
definition
(get-process | where-object{$_.name -eq "notepad"}).kill() - kills all
running notepad processes
(get-process | where-object{$_.name -eq "notepad"}) - displays the
details of all running notepad processes
get-process | select-object -property name,
@{name='procid';expression={$_.id}} - displays all of the processes,
and their ID numbers without any extra details.
get-process -name notepad | gm - show the details of the notepad
process.
get-help stop-process -full - show the full details regarding the
stop-process process
get-process | where handles -gt 1000 - show all processes that have more
than 1000 handles
get-process | where handles -gt 1000 | sort-object -property handles |
ft name, handles -autosize - shows the processes with over 1000 handles,
in a file table; putting
them in an ascending order by the number of handles
get-process | export-csv c:\stuff\proc.csv - exports the process details
to a spreadsheet
get-process | export-clixml c:\stuff\proc.xml - exports the process
details to an XML file
get-process | Format-Table/Format-List - output the data to the screen
with a default formatting
get-process | measure-object - gives how many processes are running
get-process | measure-object WS -sum -Maximum -Minimum -Average - show
these values regarding your running processes
get-process | Sort ws - shows your processes after sorting the working
set column
get-process | Sort ws -Descending - same as above; yet with the biggest
(WS) ones on top
get-process | Sort ws | Descending | select first 5 - same as above but
only the 1st 5 will show.
get-process w* | clip - takes the running processes, that start with w,
and puts them in the clipboard
get-process > procs.txt - send details about all of the working
processes to a file
get-process | out-file procs.txt - same as above command; sends details
about the processes to a file
get-process | out-gridview -PassThru | stop-process - spawns a GUI where
you can click on the process and then click OK and it will kill that
process.
get-service -Name bits, bfe - show the service (name of the) bits and
bfe services
get-service -Name b* -------- show the services that start with the
letter b
get-service -Name b*, c* -------- show the services that start with the
letter b AND c
get-service -Name bits | gm - get member (gm) shows all of the
attributes for (in this case) bits
get-service -Name bits | select -Property name, status
get-service - show all of the services
get-service -DisplayName Bit* - show the service, with the (long)
DisplayName, that has Bit in it.
get-service | export-csv -Path c:\service.csv - exports the get-service
output to an Excel spreadsheet called service.csv
get-service | ConvertTo-html -Property name,status - take the property
name and status output of get-service and output them to an xml file in
PS.
get-service | ConvertTo-html -Property name,status | out-file
c:\test.htm - same as above; but output to an html file called test.htm.
c:\test.htm -------------------------- running this after the above
will have your default browser open the test.htm file.
get-service | stop-service -whatif -- shows what would happen if you ran
this command but doesn't execute the command
get-service | stop-service -confirm - requires your confirmation before
executing the command.
get-service | where {$._.status -eq "Running"} ------- show the running
services
get-service | where {$PSItem.status -eq "Running"} - same as above
get-service | where {$PSItem.status -eq "Running" -and $_.name -like
"b*"} - show running services whose names start with a b
get-service | gm - get member (gm) will show you the properties of
whatever you pipe to it; in this case get-service
get-volume - shows the disk space and drive details
Get-WindowsFeature - show the installed feature on a server.
1) do a "Enter-PSSession servername" to get onto the server
2) run the above command to see what's on the server
Get-WindowsFeature *PowerShell* ----------------------- after doing #1
above, run this command to see which PowerShell features are installed.
- look for Windows PowerShell Web Access --------------- this needs to
be installed.
get-winevent - works in core
get-winevent -LogName security -MaxEvents 5
Get-WmiObject -class win32_bios -ComputerName (Get-ADComputer -filter *
| Select -ExpandProperty name) - this will output the running computer's
BIOS name,
Manufacturer, serial number, version and more.
Get-WmiObject -class win32_bios -ComputerName (Get-ADComputer -filter
*).name - will retrieve the same information as the immediately above
command.
Get-WmiObject -class win32_bios -ComputerName (Get-Adcomputer -filter *)
Get-WmiObject Win32_BIOS -ComputerName PC01 - access BIOS information on
PC01
Get-WmiObject Win32_BIOS -ComputerName SERVER2022DC -Credential
(Get-Credential)
Get-wmiobject -class win32_bios -ComputerName SERVER2022DC, 2019SERVER,
WINSRVR2019-2
gps |where {$_.handles -ge 1000} ----------------- show all processes
where the handles are greater than 1000
gps |where handles -ge 1000 ----------------------- same as above
Install-WindowsFeature WindowsPowerShellwebAccess - after doing #1
above, to get onto the server, run this command to install this feature.
Add-PswaAuthorizationRule * * * - after doing #1 above, and getting onto
a non-prod. server if you run this command any user from any destination
will be able to add this rule to this server.
start iexplore https://pwa/pswa - as long
as pswa is installed and everything else is in place, the pswa
application should open in a secure browser session; provided that the
certificate is in place for this to work. If it all works, you will be
able to login and put a server name into the login and get onto that
server through a (secure) browser interface.
icm dc, s1,s2 {Get-volume} | Sort Sizeremaining ------------------ show
the disk space and drive details of the 3 servers dc,s1,s2.
icm dc, s1,s2 {Get-volume} | Sort Sizeremaining | select -Last 3 - same
as above but gives only the last 3 entries
explorer - runs windows explorer
cat .\Test.ps1 - view this PowerShell script
np .\Test.ps1 -- edit this script in notepad
$procs = get-process | where handles -gt 1000 - creates
a $procs variable and assigns to it all of the processes with handles
greater that 1000
$procs - outputs (shows) the contents of the $procs
variable which are the process mentioned in the previous line
notepad procs.txt ------- open the file with notepad
remove-item .\procs.txt - same as del .\procs.txt; deletes the file
import-csv c:\service.csv - import the service.csv spreadsheet data
include the properties name and length and sort by length in a
descending order from largest to smallest.
invoke-command -ComputerName SERVER2022DC, 2019SERVER -ScriptBlock
{get-winevent -logname security -MaxEvents 5}
invoke-command -ComputerName dc,s1,s2 {get-eventlog -LogName system -new
3} - will pull the most recent 3 logs from the computers named dc,s1 and
s2.
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned - remote signs for
you.
Set-ItemProperty
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
LocalAccountTokenFilterPolicy 1 -Type DWord
- If you want to set up TrustedHosts without calling Enable-PSRemoting,
you need to add a registry key and
Set-Item WSMan:\localhost\Client\TrustedHosts –Value * -Force - add the
TrustedHosts entry
Start-Service WinRM - then temporarily run the WinRM service.
Stop-Service WinRM - stop the WinRM service
Set-ItemProperty
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
LocalAccountTokenFilterPolicy 0 -Type DWord
- revert the value of the LocalAccountTokenFilterPolicy registry entry
Your client is now able to access other systems remotely using Windows
PowerShell Remoting and is no longer limited to Kerberos and machines
inside a domain.
update-help -Force - update the help
get-verb - show all the verbs
gsv bits - show the service bits - here you are using the alias of
get-service; which is gsv
CLS ; HELP about_Eventlogs - clear the screen AND show the help file for
about_Eventlogs
HELP about_* - show help information for all of the about_ commands - go
read some of these
notepad c:\service.csv - open the Excel spreadsheet in notepad (not very
useful)
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value
'SERVER2022DC,2019SERVER,WINSRVR2019-2' - this allows remote sessions to
run on the 3 computers listed
– Ensure PSRemoting is enabled on the remote device. Past Server 2012
this is enabled by default.
Test-WsMan <Target IP> – Ensure WinRM is running on the remote device,
To determine this, run WinRM using the following command.
– Ensure the computers (servers) are added in the TrustedHosts. Instead
of adding an individual host, use the asterisk to all subsequent hosts
$PSVersionTable - tells which version of PS that you have (use in PS).
$evens.GetType().Name - what type of object is $evens?
- This returns "Object[]" indicating that it's an object/array.
$betterdate = get-date "6/10/2000 5:00 PM" - will store this date in the
variable as a System.DateTime object |
Calling .Net
Library
PowerShell
Tutorial - 1.4 - Calling .Net Library Methods
|
[System.IO.Path]::GetFileName('C:\Windows\explorer.exe)
- this is a static method of calling the library
- 1) call library (in brackets)
- 2) call the file (after the double :: marks) - with the GetFileName
command
- 3) give the path to the file being called in () marks
$Object = [System.DateTime]::Now - use the Now method of System.DateTime
and put it into the Object variable
$Object.AddHours(15) - this will add 15 hours to the
date in the variable $Object; but it won't change the variable's time or
store the output in the variable itself. The variable will stay the
same. |
-------------------------------------------------------
Working With Active Directory
-------------------------------------------------------
Get-Module -Listavailable - look at the top of the list of
modules to see if Active Directory is shown.
Get-AdGroupMember -identity "Global-Users-FileShare" |
select name
-------------------------------------------------------
VERY USEFUL CODE
-------------------------------------------------------
From cmd.exe
-----------------------------
Powershell [-noexit] "&
<path>\<script>.ps1"
pwsh -command "& .\addnumbers.ps1"
-------------------------------------------------------
WORKING WITH MODULES
-------------------------------------------------------
get-module -ListAvailable - list available modules
$env:PSModulePath - show the path/s where
the modules should be.
-------------------------------------------------------
PowerShell For Beginners Full Course |
PowerShell Beginner tutorial Full Course - 5:01:38 min. mark
------------------------------------------------------
MISCELLANEOUS
-------------------------------------------------------
$Date.GetType().Name
1) $Date - this is a variable
2) .GetType() - this is a method
3) .Name - this is a property
$Date | Format-List - format, as a list, the variable $Date;
outputs all of the properties, of the variable, in a list
format.
$Date.Year - takes the variable, $Date and
adds the Year property. The output will be the year property
of this variable.
(Get-Date).Year - same as above. This outputs the Year
property (value) of the Get-Date cmdlet.
-------------------------------------------------------
Pushing AD accounts to an AD group
-------------------------------------------------------
Add-ADGroupMember -Identity SvcAccPSOGroup -Members
SQL01,SQL02 - adds the user accounts with the SAM account
names SQL01 and SQL02 to the group SvcAccPSOGroup.
Add-ADGroupMember
https://docs.microsoft.com/en-us/powershell/module/activedirectory/add-adgroupmember?view=windowsserver2019-ps
-------------------------------------------------------
Acquiring AD Groups and Membership from one Particular Group
-------------------------------------------------------
Get-ADGroup -filter {name -like 'Admin*'} | Select name -
get AD groups, like Admin*, from a DC
Get-ADGroupMember -identity "Domain Admins" -Recursive |
Get-ADUser | select SamAccountName, Surname, GivenName - get
AD Groups like "Domain Admins"
-------------------------------------------------------
Import-Module ServerManager - import the Active Directory
module into PS
Add-WindowsFeature RSAT-AD-PowerShell - continue installing
the AD module in PS from above command
---------------------------------------------------------------------------------------------------------------
Use Get-NetFirewallRule to see a list of rules.
Moving from WMI to CIM is usually as simple as swapping the
Get-WMIObject cmdlet with Get-CIMInstance.
dism /online /get-currentedition
--------------------------------------------------------------
Run an executable remotely.
If you already have the file on the remote system, we can
run it with Invoke-Command
$command = "program.exe -r param"
Invoke-Command -ComputerName $server -ScriptBlock {$command}
invoke-command -ComputerName studio -ScriptBlock { param ( $myarg
) ping.exe $myarg } -ArgumentList localhost
An example of invoking a program that is not in the path and
has a space in it's folder path:
invoke-command -ComputerName Computer1 -ScriptBlock { param
($myarg) & 'C:\Program Files\program.exe' -something $myarg
} -ArgumentList "myArgValue"
If the value of the argument is static you can just provide
it in the script block like this:
invoke-command -ComputerName Computer1 -ScriptBlock { &
'C:\Program Files\program.exe' -something "myArgValue" }
cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"
$s = New-PSSession -computername NAME -credential LOGIN
Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s
------------------------------------------------------
start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"
Here I place it in the windows temp folder then remotely
execute it.
Copy-Item -Path $file -Destination "\\$computername\c$\windows\temp\installer.exe"
Invoke-Command -ComputerName $computerName -ScriptBlock {
c:\windows\temp\installer.exe /silent
}
------------------------------------------------------
Pre-copy using PSSession (PS 5.0)
$session = New-PSSession -ComputerName $computerName
Copy-Item -Path $file -ToSession $session -Destination
'c:\windows\temp\installer.exe'
Invoke-Command -Session $session -ScriptBlock {
c:\windows\temp\installer.exe /silent
}
Remove-PSSession $session
------------------------------------------------------
While you can run Invoke-Command on multiple computers at
once, be aware that Copy-Item -ToSession only works on a
single session.
------------------------------------------------------
$credential = Get-Credential
$psdrive = @{
Name = "PSDrive"
PSProvider = "FileSystem"
Root = "\\fileserver\share"
Credential = $credential
}
Invoke-Command -ComputerName $computerName -ScriptBlock {
New-PSDrive @using:psdrive
\\fileserver\share\installer.exe /silent
}
------------------------------------------------------
# For ServerC in Contoso domain and ServerB in other domain
$ServerB = Get-ADComputer -Identity ServerB
-Server dc1.alpineskihouse.com
$ServerC = Get-ADComputer -Identity ServerC
Set-ADComputer -Identity $ServerC -PrincipalsAllowedToDelegateToAccount
$ServerB
#To undo the configuration, reset ServerC’s attribute to
null.
Set-ADComputer -Identity $ServerC -PrincipalsAllowedToDelegateToAccount
$null
------------------------------------------------------
Install-Package $PackageName
------------------------------------------------------
choco install $PackageName
------------------------------------------------------
You can set up a nuget repository and use the new package
management commands to deploy applications. If you have
an internal dev team, this is something they may have
already set up
Install-Package $PackageName -Source MyRepoName
------------------------------------------------------
package management
------------------------------------------------------
PS C:\> get-packageprovider - show your package providers
PS C:\> Get-PackageSource - each provider will have a source
Find-Package -ProvederName Chocolatey notepad
- this command searches Chocolatey for notepad to see if
that provider has that application.
choco install notepadplusplus.install
--------------------------------------------------------------------------------------------------
Installing the Get-ADComputer cmdlet
-----------------------------------------------
1) get-module -listavailable - show a list of available
modules
2) import-module activedirectory - if the ActiveDirectory
module is present this command will add it; if not do the
following 2 steps - run each line separately; not together
as one line
3) Import-Module ServerManager - run this command to import
the ServerManager module (which will be present)
4) Add-WindowsFeature RSAT-AD-PowerShell - install the
ActiveDirectory module
----------------------------------------------------------------------------------------
VARIABLES
----------------------------------------------------------------------------------------
PS C:\> $MyVar="Hello" - create a variable and fill it with
Hello.
- type $MyVar after the above and the response will be the
content, Hello.
PS C:\> $MyVar=Get-service bits - puts the Get-service bits
object into the variable
PS C:\> $MyVar | gm ------ will show the details for the
Get-service bits object that's now in the variable.
PS C:\> $MyVar.status ---- will return the operational
status of the Get-service bits controller object
PS C:\> $MyVar.stop() ---- will stop the service controller
if it's running.
PS C:\> $MyVar.start() ---- will start the service
controller.
PS C:\> $MyVar.refresh() - will refresh the status of the
object
PS C:\> $MyVar.status ----- should give the proper status,
of it, if it's now running; which it should be.
- if the controller object is stopped and you try stopping
it, it will give you an error. You can start if it
it's stopped and stop it if it's started; without any
error/s.
PS C:\> $var=read-host "Enter a ComputerName" - read-host
reads the host. adding this to the variable with this text
will return this text and want you to type in what the
host/computer name is. It will return the following.
Enter a computerName:
If you enter (type in) the name dc, as the computer name,
this will be what is now in the $var variable.
PS C:\> get-service -name bits -ComputerName $var - typing
this in, now, will give you the bits service status on the
server dc; if you have a server with that name.
Invoke-Command -ComputerName S1, S2, S3 -ScriptBlock
{Get-Culture} - run the Get-Culture command on 3 computers.
Windows PowerShell establishes a connection just for the
command. Then, it closes the connection when the command is
complete. Any variables or functions that are defined in the
command are lost.
$s = New-PSSession -ComputerName Server01, Server02 -
creates PSSessions on the Server01 and Server02 computers
and then saves the PSSessions in the $s variable. To create
a persistent connection to a remote computer, use the New-PSSession
cmdlet.
$s = New-PSSession -ComputerName S1, S2, S3
Invoke-Command -Session $s -ScriptBlock {Get-Culture}
- these two commands (when executed) create PSSessions on
the Server01, Server02, and Server03 computers and
then runs a Get-Culture command in each of the PSSessions. |
|
|
|
| |