windows powershell 4.0 による windows server 2012 r2 の 管理 ~ hyper-v 編

Click here to load reader

Upload: penny

Post on 09-Feb-2016

386 views

Category:

Documents


1 download

DESCRIPTION

勉強会キット. Windows PowerShell 4.0 による Windows Server 2012 R2 の 管理 ~ Hyper-V 編. 第一版 2013.12.01. 日本マイクロソフト株式会社 エバンジェリスト 安納 順一 Junichi Anno BLOG http://blogs.technet.com/junichia/. はじめに. この勉強会キットでは、 Windows PowerShell を使用してリモートコンピューターから Hyper-V を管理するための手法を学習します。 - PowerPoint PPT Presentation

TRANSCRIPT

1

Windows PowerShell 4.0 Windows Server 2012 R2 Hyper-V Junichi AnnoBLOG http://blogs.technet.com/junichia/ 2013.12.01#Windows PowerShell Hyper-V Windows Server 2012 R2 Hyper-V Server 2012 R2 OS

3

1 OS PowerShell Hyper-V 2 1 Hyper-V 3 Windows PowerShell 12Windows PowrShell Windows Server #Windows Server 2012 R2(GUI)Hyper-V Server 2012 R2IP Windows PowerShell Windows Server 2012 R2Sysprep OS OSVHDhttp://technet.microsoft.com/ja-jp/evalcenter/dn205286.aspx212#Agenda1 OS PowerShell Hyper-V

2 1 Hyper-V

3 Windows PowerShell 12Windows PowrShell Windows Server #1 OS Windows PowerShell Hyper-V #1 Windows Server

Windows Server 2012 R2

Windows PowerShell

Windows Server IP DNS Windows Update

Hyper-V Hyper-V Hyper-V Hyper-V

DNS DNS DNS

Active Directory AD DS Active Directory

DHCP Server DHCP DHCP

OS OS OS

#1.Windows Server 2012 R2 Windows Server 2012 R2 GUI Windows PowerShell Windows PowerShell

#2. Windows PowerShell Windows Server 2012 R2 Windows PowerShell PowerShell Windows PowerShell ISE ISE

[Ctrl]+[+] [Ctrl] + [-] #PS C:\>Set-ExecutionPolicy RemoteSignedPS C:\>Enable-PSRemoting forcePowerShell #3. Windows Server IP IP InterfaceIndex

InterfaceIndex = 13

DHCP IP

PS C:\>New-NetIPAddress -InterfaceIndex 13 -IPAddress 192.168.0.1 -AddressFamily IPv4 -PrefixLength 24 -DefaultGateway 192.168.0.254 DefaultGateway Set-NetIPAddress PS C:\> Get-NetAdapter | FT Name, InterfaceIndex, InterfaceDescription PS C:\> Get-NetIPAddress -InterfaceIndex 13 -AddressFamily IPv4#PS C:\>Set-DnsClientServerAddress -Interface 24 -ServerAddress 192.168.0.1DNS DNS PS C:\> Remove-IPAddress -InterfaceIndex 24 -AddressFamily IPv4IP PS C:\> Set-DnsClientServerAddress -Interface 24 -ResetServerAddressDNSPS C:\> Set-NetIPInterface -InterfaceIndex 24 -Dhcp EnabledDHCP DNS #PS C:\> $Env:ComputerName

PS C:\> Rename-Computer -NewName HV01 -Force -Restart #Windows Update Windows Update PowerShell Module

Windows Update PowerShell Module http://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bcWindows Update PowerShell Modules PSWindowsUpdate.zip C:\tmp

Dir PSWindowsUpdate PS C:\> Add-Type -AssemblyName System.IO.Compression.FileSystemPS C:\> $ZipFile = Get-Item C:\tmp\PSWindowsUpdate.zipPS C:\> [IO.Compression.ZipFile]::ExtractToDirectory( $ZipFile, C:\tmp )PS C:\> $web = New-Object System.Net.WebClientPS C:\> $zipfile = "http://gallery.technet.microsoft.com/scriptcenter/PS C:\> $zipfile = $zipfile + 2d191bcd-3308-4edd-9de2-88dff796b0bc/file/41459/28/PSWindowsUpdate.zip"PS C:\> $web.DownloadFile($zipfile, "C:\tmp\PSWindowsUpdate.zip") #

PowerShell

C:\Users\junichia\Documents\WindowsPowerShell\Modules PowerShell PS C:\>$env:PSModulePathC:\Users\Administrator\Documents\WindowsPowerShell\Modules;C:\windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\PS C:\> md C:\Users\Administrator\Documents\WindowsPowerShell\ModulesPS C:\>Unblock-File \*.*PS C:\>Unblock-File c:\tmp\PSWindowsUpdate\*.*# PSWindowsUpdate C:\Users\Administrator\Documents\WindowsPowerShell\Modules PSWindowsUpdate C:\tmp

PSWindowsUpdate

Windows Update

PS C:\> Move C:\tmp\PSWindowsUpdate C:\Users\Administrator\Documents \WindowsPowerShell\ModulesPS C:\> Import-Module PSWindowsUpdatePS C:\> Get-WUInstall -AcceptAll#4. Hyper-V Hyper-V

Hyper-V

Hyper-V

PS C:\> Get-WindowsFeature PS C:\> Add-WindowsFeature Hyper-V -IncrudeAllSubFeature -IncludeManagementTools -RestartPS C:\> Get-Command -Module Hyper-V#Hyper-V Hyper-V

D:\VM

PS C:\> Set-VMHost -VirtualHardDiskPath D:\VMPS C:\> Set-VMHost -VirtualMachinePath D:\VMPS C:\> Get-VMHost | FL#Hyper-VHyper-V

Hyper-V Kerberos

D:\VM

Windows Firewall

PS C:\> Get-VMReplicationServer | FLPS C:\> Set-VMReplicationServer -ReplicationEnabled $True -AllowedAuthenticationType KerberosPS C:\> Set-VMReplicationServer -ReplicationAllowedFromAnyServer $True -DefaultStorageLocation D:\VMPS C:\> Get-NetFirewallRule -Direction Inbound#Windows Firewall Hyper-V

HTTP HTTPS HTTP VIRT-HVRHHTTPL-In-TCP-NoScopeHTTPS VIRT-HVRHHTTPSL-In-TCP-NoScope

Hyper-V HTTP TCP

PS C:\> Get-NetFirewallRule -Direction Inbound -Desctiption **PS C:\> Set-NetFirewallRule -Name VIRT-HVRHTTPL-In-TCP-NoScope -Enabled True$ #

Name

ExternalSwitch

Hyper-V NIC ExternalSwitch

vEthernet (ExternalSwitch) NIC

PS C:\> Get-VMSwitchPS C:\> New-VMSwitch -Name ExternalSwitch -NetAdapterInterName -AllowManagementOS $TruePS C:\> Get-NetAdapter | FLPS C:\> Get-NetAdapter | FL#5. DNS DNSDNS

DNS

DNS

Active Directory PS C:\> Add-WindowsFeature dns -IncludeManagementTools -IncrudeAllSubFeature -RestartPS C:\> Get-Command *DNSServer*PS C:\> Get-DNSServerZone#216. Active Directory Active Directory Domain Service AD DSAD DS

AD DS

Active Directory Contoso.com

SecureString $Password P@ssw0rd

PS C:\> Add-WindowsFeature AD-Domain-Services -IncludeManagementTools -IncrudeAllSubFeature -RestartPS C:\> Get-Command -module ActiveDirectoryPS C:\> Import-Module ADDSDeploymentPS C:\> $Password = ConvertTo-SecureString P@ssw0rd -AsPlainText -Force# 1

PS C:\> Install-ADDSForest -CreateDnsDelegation:$False -DatabasePath C:\Windows\NTDS -DomainMode Win2012R2 -DomainName contoso.com -DomainNetbiosName CONTOSO -ForestMode Win2012R2 -InstallDns:$True -LogPath C:\Windows\NTDS -NoRebootOnCompletion:$False -SysvolPath C:\Windows\Sysvol -SafeModeAdministratorPassword $Password -Force:$True#Contoso.com

PS C:\> Get-DNSServerZone -Name contoso.com | FL#7. DHCP DHCP DHCP DHCP

-Restart DHCPDHCP

PS C:\> Add-WindowsFeature DHCP -IncrudeAllSubFeature -IncludeManagementTools -RestartPS C:\> Get-Command *DHCP*#DHCP DHCP 192.168.0.1 NIC DHCP IP

BindingState True DHCP 192.168.0.1 Get-NetAdapter NIC Name -InterfaceAlias NIC Name

DHCP Active Directory

DHCP Netsh PS C:\> Get-DHCPServerV4BindingPS C:\>Set-DHCPServerV4Binding -InterfaceAlias vEthernet (ExternalSwitch) -BindingState $TruePS C:\> Add-DHCPServerInDC -DnsName contoso.comPS C:\> Netsh dhcp add SecurityGroups#DHCP

DHCP PS C:\> Restart-Service DHCPServerPS C:\> Set-ItemProperty Path registry::HKLM\SOFTWARE\Microsoft\ServerManager\Roles\12 Name ConfigurationState Value 2#IPV4

Scope ID 192.168.0.0

DNS Server PS C:\>Get-DHCPServerV4Scope PS C:\> Set-DhcpServerV4ScopeOptionValue -ScopeID 192.168.0.0 -DnsServer 192.168.0.1 PS C:\>Add-DHCPServerV4Scope -StartRange 192.168.0.10 -EndRange 192.168.0.20 -SubnetMask 255.255.255.0 -Name Scope for VMs -State Active#8. OS OS

OS VM01 OS D:\VMs\VM01.vhd

PS C:\> Get-VM OS OSPS C:\> New-VM -Name VM01 -MemoryStartupBytes 1024MB -VHDPath D:\VMs\VM01.vhd -SwitchName ExternalSwitch -Generation 1 -BootDevice IDE#OS VM01

CPU 2

OS

PS C:\> Get-VM -Name VM01 | FLPS C:\> Set-VM -Name VM01 -ProcessorCount 2 -DynamicMemoryPS C:\> Start-VM VM01# OS OS

OS Sysprep Windows Server 2012 R2 VHD

Hyper-V Hyper-V OS VM01

OOBE En-US 101/102 P@ssw0rd 101/102 @ [Shift] + [2] OS PowerShell

OS PowerShell

PS C:\> Enable-PSRemoting -ForcePS C:\> netsh advfirewall firewall set rule group=network discovery new enable=yes# OS Hyper-V OSHyper-V TrustedHosts

OSOS P@ssw0rd

OSIP

OS OS VM01 DHCP 192.168.0.11

PS C:\> Set-Item WSMan:\localhost\Client\TrustedHosts 192.168.0.* -Concatenate PS C:\> Get-DhcpServerV4Lease -ScopeId 192.168.0.0PS C:\> $Pass = ConvertTo-SecureString P@ssw0rd -AsPlainText -ForcePS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user, $passPS C:\> $User = AdministratorPS C:\> Enter-PSSession 192.168.0.11 -Credential $Cred#OS InterfaceIndex OS

OS IPInterfaceIndex = 12 PrefixOrigin DHCPOS

OS IP 192.168.0.100 OS

OSIP[Ctrl]+[C]

[192.168.0.11] :PS C:\> Get-NetAapter[192.168.0.11] :PS C:\> New-NetIPAddress -InterfaceIndex 12 -IPAddress 192.168.0.100 -AddressFamily IPv4 -PrefixLength 24 [192.168.0.11] :PS C:\> Get-NetIPAddress -InterfaceIndex 12 -AddressFamily IPv4#OS

DNSOS

OS

[192.168.0.100] :PS C:\> Rename-Computer -NewName HV01 -Force -Restart PS C:\> $User = AdministratorPS C:\> $Pass = ConvertTo-SecureString P@ssw0rd -AsPlainText -ForcePS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user, $passPS C:\> Enter-PSSession 192.168.0.100 -Credential $Cred[192.168.0.100] :PS C:\>[192.168.0.100] PS C:\>Set-DnsClientServerAddress -Interface 12 -ServerAddress 192.168.0.1[192.168.0.100] :PS C:\> ExitPS C:\>#VM01 DNS

OSPS C:\> Add-DnsServerResourceRecordA -Name VM01 -IPAddress 192.168.0.100 -ZoneName contoso.comPS C:\> $User = AdministratorPS C:\> $Pass = ConvertTo-SecureString P@ssw0rd -AsPlainText -ForcePS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user, $passPS C:\> Enter-PSSession 192.168.0.100 -Credential $Cred[192.168.0.100] :PS C:\>#VM01 OS

[192.168.0.100] :PS C:\> $Domain = contoso.com[192.168.0.100] :PS C:\> $Client = $Env:COMPUTERNAME[192.168.0.100] :PS C:\> $User = Administrator[192.168.0.100] :PS C:\> $Pass = ConvertTo-SecureString P@ssw0rd -AsPlainText -Force[192.168.0.100] :PS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user , $pass[192.168.0.100] :PS C:\> $DomainUser = Contoso\Administrator[192.168.0.100] :PS C:\> $DomainPass = ConvertTo-SecureString P@ssw0rd -AsPlainText -Force[192.168.0.100] :PS C:\> $DomainCred = New-Object System.Management.Automation.PSCredential $DomainUser , $DomainPass[192.168.0.100] :PS C:\> Add-Computer -ComputerName $Clienit -LocalCredential $Cred -Credential $DomainCred -DomainName $Domain[192.168.0.100] :PS C:\> ExitPS C:\># VM01

VM01

PS C:\> Restart-VM VM01 -Force PS C:\> Enter-PSSession VM01[VM01]: PS C:\>[VM01]: PS C:\> ExitPS C:\>#2 1 Hyper-V 1 Windows PowerShell #2 Windows ServerHyper-V Server 2012 R2

Windows PowerShell

Windows Server IP DNS Active Directory Windows Update

Hyper-V PowerShell Hyper-V Hyper-V

1 HV01

Hyper-V Windows Server Hyper-V Server 2012 R2 #9. Hyper-V Server 2012 R2 2 PC Hyper-V Windows Server 2012 R2

Hyper-V Server 2012 R2

Hyper-V Server 2012 R2 Hyper-V #10. Windows PowerShell Hype-V Server 2012 R2 ISE

Hyper-V Server 2012 R2 PowerShell PS

PowerShell

C:\> PowerShellPS C:\>PS C:\>Set-ExecutionPolicy RemoteSignedPS C:\>Enable-PSRemoting force#11. Hyper-V Server IP IP InterfaceIndex

InterfaceIndex = 13

DHCP IP

PS C:\>New-NetIPAddress -InterfaceIndex 13 -IPAddress 192.168.0.2 -AddressFamily IPv4 -PrefixLength 24 DefaultGateway Set-NetIPAddress PS C:\> Get-NetAdapter | FT Name, InterfaceIndex, InterfaceDescription PS C:\> Get-NetIPAddress -InterfaceIndex 13 -AddressFamily IPv4#PS C:\>Set-DnsClientServerAddress -Interface 13 -ServerAddress 192.168.0.1DNS DNS PS C:\> Remove-IPAddress -InterfaceIndex 24 -AddressFamily IPv4IP PS C:\> Set-DnsClientServerAddress -Interface 24 -ResetServerAddressDNSPS C:\> Set-NetIPInterface -InterfaceIndex 24 -Dhcp EnabledDHCP DNS #

PowerShell

PS C:\> $Env:ComputerNamePS C:\> Rename-Computer -NewName HV02 -Force -Restart C:\> PowerShellPS C:\>#Hyper-V Server HV02 Contoso

contoso\administratorPS C:\> $Domain = contoso.comPS C:\> $Client = $Env:COMPUTERNAMEPS C:\> $User = AdministratorPS C:\> $Pass = ConvertTo-SecureString P@ssw0rd -AsPlainText -ForcePS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user , $passPS C:\> $DomainUser = Contoso\AdministratorPS C:\> $DomainPass = ConvertTo-SecureString P@ssw0rd -AsPlainText -ForcePS C:\> $DomainCred = New-Object System.Management.Automation.PSCredential $DomainUser , $DomainPassPS C:\> Add-Computer -ComputerName $Clienit -LocalCredential $Cred -Credential $DomainCred -DomainName $DomainPS C:\> Restert-Computer#Windows Update Windows Update PowerShell Module

Windows Update PowerShell Module http://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bcWindows Update PowerShell Modules PSWindowsUpdate.zip C:\tmp

Dir PSWindowsUpdate PS C:\> Add-Type -AssemblyName System.IO.Compression.FileSystemPS C:\> $ZipFile = Get-Item C:\tmp\PSWindowsUpdate.zipPS C:\> [IO.Compression.ZipFile]::ExtractToDirectory( $ZipFile, C:\tmp )PS C:\> $web = New-Object System.Net.WebClientPS C:\> $zipfile = "http://gallery.technet.microsoft.com/scriptcenter/PS C:\> $zipfile = $zipfile + 2d191bcd-3308-4edd-9de2-88dff796b0bc/file/41459/28/PSWindowsUpdate.zip"PS C:\> $web.DownloadFile($zipfile, "C:\tmp\PSWindowsUpdate.zip") #

PowerShell

C:\Users\junichia\Documents\WindowsPowerShell\Modules PowerShell PS C:\>$env:PSModulePathC:\Users\Administrator\Documents\WindowsPowerShell\Modules;C:\windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\PS C:\> md C:\Users\Administrator\Documents\WindowsPowerShell\ModulesPS C:\>Unblock-File \*.*PS C:\>Unblock-File c:\tmp\PSWindowsUpdate\*.*# PSWindowsUpdate C:\Users\Administrator\Documents\WindowsPowerShell\Modules PSWindowsUpdate C:\tmp

PSWindowsUpdate

Windows Update

PS C:\> Move C:\tmp\PSWindowsUpdate C:\Users\Administrator\Documents \WindowsPowerShell\ModulesPS C:\> Import-Module PSWindowsUpdatePS C:\> Get-WUInstall -AcceptAll#12. Hyper-V Hyper-V Server Hyper-VPowerShell

Windows PowerShell Hyper-V

Windows PowerShell Hyper-V

Hyper-V

PS C:\> Get-WindowsFeature PS C:\> Add-WindowsFeature Hyper-V-PowerShell -IncludeAllSubFeature PS C:\> Get-Command -Module Hyper-V#Hyper-V Hyper-V

E:\VM

PS C:\> Set-VMHost -VirtualHardDiskPath E:\VMPS C:\> Set-VMHost -VirtualMachinePath E:\VMPS C:\> Get-VMHost | FL#Hyper-VHyper-V

Hyper-V Kerberos

E:\VM

Windows Firewall

PS C:\> Get-VMReplicationServer | FLPS C:\> Set-VMReplicationServer -ReplicationEnabled $True -AllowedAuthenticationType KerberosPS C:\> Set-VMReplicationServer -ReplicationAllowedFromAnyServer $True -DefaultStorageLocation E:\VMPS C:\> Get-NetFirewallRule -Direction Inbound#Windows Firewall Hyper-V

HTTP HTTPS HTTP VIRT-HVRHHTTPL-In-TCP-NoScopeHTTPS VIRT-HVRHHTTPSL-In-TCP-NoScope

Hyper-V HTTP TCP

PS C:\> Get-NetFirewallRule -Direction Inbound -Desctiption **PS C:\> Set-NetFirewallRule -Name VIRT-HVRHTTPL-In-TCP-NoScope -Enabled True$ #HV01

Name

ExternalSwitch

Hyper-V NIC ExternalSwitch

vEthernet (ExternalSwitch) NIC PS C:\> New-VMSwitch -Name ExternalSwitch -NetAdapterInterName -AllowManagementOS $TruePS C:\> Get-NetAdapter | FLPS C:\> Get-NetAdapter | FL# ExternalSwitch PS C:\> Get-VMSwitch#13. HV01 HV02 HV01 PowerShell ISE Windows Server 2012 R2(GUI)Hyper-V Server 2012 R2HV01 192.168.0.1Windows Server 2012 R2Hyper-VAD DSDNSDHCPHV02 192.168.0.2Hyper-VExternalSwitchExternalSwitchVM01 192.168.0.3Active Directory Contoso.com# HV01

Hyper-V HV01 HV02

KerberosPS C:\> Enable-VMMigration -ComputerName HV01, HV02Set-VMHost -ComputerName HV01, HV02 -UseAnyNetworkForMigration $TrueSet-VMHost -ComputerName HV01, HV02 -VirtualMachineMigrationAuthenticationType Kerberos Set-VMHost -ComputerName HV01, HV02 -VirtualMachineMigrationPerformanceOption Compression# 10

HV01 VM01

PC C:\> Set-VMHost -ComputerName HV01, HV02 -MaximumVirtualMachineMigrations 10PS C:\> Set-VMProcessor -ComputerName HV01 -VMName VM01 -CompatibilityForMigrationEnabled $TruePS C:\> Stop-VM -ComputerName HV01 -Name VM01PS C:\> Start-VM -ComputerName HV01 -Name VM01#Kerberos

2 CIFSMicrosoft Virtual System Migration ServiceHyper-V over SMB CIFS HV01 HV02 HV01HV02CIFSMicrosoft Virtual System Migration ServiceCIFSMicrosoft Virtual System Migration Service#HV01 HV02 CIFS

HV02 HV01 CIFS PS C:\> $TargetServer = HV01PS C:\> $TargetServerDN = (Get-ADComputer $TargetServer)PS C:\> $HVServer = Get-ADComputer HV02PS C:\> $HVServerName = $HVServer.NamePS C:\> $HVServerDNS = $HVServer.DNSHostNamePS C:\> Set-ADObject -Identity $TargetServerDN -Add @{ msDS-AllowedToDelegateTo = cifs/$HVServerName, cifs/$HVServerDNS }PS C:\> $TargetServer = HV02PS C:\> $TargetServerDN = (Get-ADComputer $TargetServer)PS C:\> $HVServer = Get-ADComputer HV01PS C:\> $HVServerName = $HVServer.NamePS C:\> $HVServerDNS = $HVServer.DNSHostNamePS C:\> Set-ADObject -Identity $TargetServerDN -Add @{ msDS-AllowedToDelegateTo = cifs/$HVServerName, cifs/$HVServerDNS }#HV01 HV02 Microsoft Virtual System Migration

HV02 HV01 Microsoft Virtual System Migration PS C:\> $ServiceName = Microsoft Virtual System Migration ServicePS C:\> $TargetServer = HV01PS C:\> $TargetServerDN = (Get-ADComputer $TargetServer)PS C:\> $HVServer = Get-ADComputer HV02PS C:\> $HVServerName = $HVServer.NamePS C:\> $HVServerDNS = $HVServer.DNSHostNamePS C:\> Set-ADObject -Identity $TargetServerDN -Add @{ msDS-AllowedToDelegateTo = $ServiceName/$HVServerName, $ServiceName/$HVServerDNS }PS C:\> $ServiceName = Microsoft Virtual System Migration ServicePS C:\> $TargetServer = HV02PS C:\> $TargetServerDN = (Get-ADComputer $TargetServer)PS C:\> $HVServer = Get-ADComputer HV01PS C:\> $HVServerName = $HVServer.NamePS C:\> $HVServerDNS = $HVServer.DNSHostNamePS C:\> Set-ADObject -Identity $TargetServerDN -Add @{ msDS-AllowedToDelegateTo = $ServiceName/$HVServerName, $ServiceName/$HVServerDNS }#HV02

HV01 HV02

PS C:\> Restart-Computer -ComputerName HV02 -Wait -ForcePS C:\> Restart-Computer -Force#

VM01 HV01

VM01 HV02 HV02 E:\VM\VM01

VM01 HV02

PS C:\> Get-VM -ComputerName HV01PS C:\> Move-VM -ComputerName HV01 -Name VM01 -DestinationHost HV02 -IncludeStorage -DestinationStoragePath E:\VM\VM01PS C:\> Get-VM -ComputerName HV01#3 Hyper-V Windows PowerShell Visual Studio#3 ~ PowerShell Part1 Windows PowerShell Tips

Part2 -ComputerNamePS PSWindows PowerShell Web AccessPSWA)

Part3 10.

Part4 Windows PowerShell Workflow Windows PowerShell Workflow

Part5 Windows PowerShell Windows PowerShell Visual StudioC# PowerShell Windows PowerShell #Part 1 #1. Windows PowerShell #Windows PowerShell Windows Familiar Windows ScriptWSHWinRM

Windows Familiar

Non-Windows Familiar OMIOpen Management Infrastructure# .batVBScript .vbsPowerShell .ps1Jscript .jsMS-DOSVisual Basic VisualVisual VBA JavaScript MS VBScript JavaScript Microsoft .NET Framework PowerShellWindows Script Host Server CoreWindows ScriptOS#Windows.NET FrameworkPowerShell exebatVBScriptJScriptScript Engine

CLRClass LibraryPowerShell COMcmd/commandWindows Script HostCscript.exeWscript.exeCOM#cmd.execommand.comNTDOS/Win312000XP/2003Vista/2008Windows Script HostPowerShell bat/vbs/js Win9x/MeWin7/2008R2Windows PowerShell1002002300#VBScript vs PowerShellExchange 2003 (VBScript)Exchange 2007PowerShell

Set listExchange_Mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2").InstancesOf("Exchange_Mailbox")

For Each objExchange_Mailbox in listExchange_MailboxsWScript.echo "AssocContentCount = + objExchange_Mailbox.AssocContentCountWScript.echo " DateDiscoveredAbsentInDS = + objExchange_Mailbox.DateDiscoveredAbsentInDSWScript.echo " DeletedMessageSizeExtended =" + objExchange_Mailbox.DeletedMessageSizeExtendedWScript.echo " LastLoggedOnUserAccount =" + objExchange_Mailbox.LastLoggedOnUserAccountWScript.echo " LastLogoffTime =" + objExchange_Mailbox.LastLogoffTimeWScript.echo " LastLogonTime =" + objExchange_Mailbox.LastLogonTime WScript.echo " LegacyDN =" + objExchange_Mailbox.LegacyDNWScript.echo " MailboxDisplayName = + objExchange_Mailbox. MailboxDisplayNameWScript.echo " MailboxGUID =" + objExchange_Mailbox.MailboxGUID WScript.echo " ServerName =" + objExchange_Mailbox.ServerName WScript.echo " Size =" + objExchange_Mailbox.SizeWScript.echo " StorageGroupName =" + objExchange_Mailbox.StorageGroupName WScript.echo " StorageLimitInfo =" + objExchange_Mailbox.StorageLimitInfo WScript.echo " StoreName =" + objExchange_Mailbox.StoreName WScript.echo " TotalItems =" + objExchange_Mailbox.TotalItems Nextget-mailboxstatistics server $servername

Dim StorGroup as New CDOEXM.StorageGroup

StorGroup.DataSource.Open "LDAP://" + DCServer + "/ CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName

StorGroup.MoveLogFiles("C:\newlogPath", 0)move-storagegrouppath -identity "First Storage Group" log "C:\newlogPath"Dim objMailbox As CDOEXM.IMailboxStore

Set objMailbox = GetObject("LDAP://" + DCServer + "CN=FOO,CN=users," + DomainName)

objMailbox.CreateMailbox "LDAP://" + DCServer + "/CN=Private MDB,CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainNameenable-mailbox -identity domain\FOO database "First Storage Group\Private MDB"#WBEM - Web Based Enterprise Managementhttp://www.dmtf.org/standards/wbemDMTFDesktop Management Task ForceWeb OS SNMPSimple Network Management Protocol syslog HTTP XML Windows HP-UX OSHP OpenView http://h50146.www5.hp.com/products/software/oe/hpux/developer/column/smh_02/#

http://h50146.www5.hp.com/products/software/oe/hpux/developer/column/smh_02/HP WBEM #

http://docs.oracle.com/cd/E19455-01/806-7119/6jg10nqef/index.htmlSolaris WBEM #Microsoft

#History of Microsoft Management Framework2000 Windows 2000 WMI 29 WMI Windows NT, 98, 95 WMI 15 WMI Windows

2005 WS-Management DMTF 2007 Windows Server 2008 WS-Management WinRMHTTP/S Windows PowerShell WinRM WS-Management Web Services for Management Windows Server #Windows Management Frameworkhttp://www.microsoft.com/downloads/Windows PowerShell ISE Microsoft .NET Framework 4.0 OSWMF 3.0WMF 4.0Windows 7SP1 SP1 Windows Server 2008SP2 Windows Server 2008 R2SP1 SP1 Windows 8Windows 8.1Windows Server 2012Windows Server 2012 R2#Windows Management FrameworkWindows Management FrameworkIT ProIT DeveloperSolutionDeveloperStorageNetworkDevicesCPUWindows PowerShellCIMOMSMI-SWS-ManagementWinRM(Web Service for Management)httpService ProviderWS-ManCIMOMSMI-SSMI-SStorage Management Initiative - Specification#78The Open Group Membership 2012/10/5 Platinum - 5Capgemini NetherlandsHewlett-Packard USAIBM USAKingdee Software (China) Co. Ltd ChinaOracle Corporation USAGold 44Microsoft Corporation USANTT Data CorporationReGIS Inc.Silver 256 Japan Asahi Techneion Co., LtdAXE, Inc.eflow Inc.Information-technology Promotion Agency, JapanJapan Aerospace Exploration Agency (JAXA)Mizuho Information and Research Institute, Inc.Nissan Motor Co., Ltd.Nomura Research Institute, Ltd.Rococo Co LtdSIOS Technology, Inc.Sony CSLSymphony Ltd.Academic 38 Japan Aoyama Gakuin UniversityKyoto UniversityNagoya UniversityThe University of Tokyo Information Technology Center

#Open Management InfrastructurenanoWBEM CIM Server 250KBC Windows PowerShellProviders : CIMOM,SMI-SWS-Management(OMI)Providers : CIMOM,SMI-SStorageNetworkDevicesCPUStorageNetworkDevicesCPUWS-ManagementWinRMWinRM ClientWinRM ServerOMI ClientOMI Server#

#OMI HP-UX 11i v2 and v3 (PA-RISC and IA64) Sun Solaris 8 and 9 (SPARC) and Solaris 10 (SPARC and x86) Red Hat Enterprise Linux 4 (x86/x64) and 5 (x86/x64) Server Novell SUSE Linux Enterprise Server 9 (x86) and 10 SP1 (x86/x64) IBM AIX v5.3 and v6.1 (POWER) MacOS 10.5 (Intel) Windows OMI Source - v.1.0.7a 20135#http://www.opengroup.org/

# Windows PowerShell GUI Active DirectoryActive DirectoryPowerShell ModuleActive Directory Hyper-VHyper-VPowerShell ModuleSystem Center Virtual Machine ManagerPowerShell#Windows PowerShell ISEPowershell_ise.exeWindows PowerShell IntelliSense

#2. #

PS C:\>Set-ExecutionPolicy RemoteSignedPS C:\>Enable-PSRemoting forcePS C:\>notepad $profile#87 Set-ExecutionPolicy Restricted ()AllSignedRemoteSigned UnrestrictedBypasshttp://technet.microsoft.com/ja-jp/library/dd347628.aspxScope

#13/12/1 1936882005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.Checkpoint-VMCompare-VMExport-VMGet-VMImport-VMMeasure-VMMove-VMNew-VMRemove-VMRename-VMRepair-VMRestart-VMResume-VMSave-VMSet-VMStart-VMStop-VMSuspend-VM-#PowerShell ModuleImport-Module ModuleCmdLetCmdLetCmdLetCmdLetHyper-VAdd-VMDvdDriveAdd-VMFibreChannelHbaAdd-VMHardDiskDriveAdd-VMMigrationNetworkAdd-VMNetworkAdapterAdd-VMNetworkAdapterAclMicrosoft.PowerShell.ManagementAdd-ComputerAdd-ContentCheckpoint-ComputerClear-ContentClear-EventLogClear-ItemClear-ItemPropertyComplete-Transaction#

PS C:\> Get-ModulePS C:\> Get-Module -ListAvailable PS C:\> Import-Module PS C:\> Import-Module Hyper-VPS C:\> Import-Module (Get-Module -ListAvailable).Name #

-VM

PS C:\> Get-CommandPS C:\> Get-Command *-vm* -CommandType Cmdlet PS C:\> Get-Command -Module Hyper-VPS C:\> Get-Help -detailedPS C:\> Get-Help Move-VM -detailed#

DOSLinux

PS C:\> Get-Alias#PowerShell Get-Servicestop()#...

#Windows DisplayNameStatusDependentServicesStop()Start()Pause()MachineNameWindows

#

COMNew-Object -com scripting.filesystemobject | Get-Member

| get-member | get-member | sort-object Name | format-listGet-Service | Get-MemberGet-VM | Get-Member#TIPS ...PS C:\>$a = abc

# $a ...#

PS C:\>$a.ToUpper()PS C:\>ABCPS C:\>$a.ToUpper().Split("B")[0]PS C:\>A

#PS C:\> (ipconfig)[18].Split(":")[1].Trim()objectipconfig 180

IPv4 . . . . . . . . . . : 192.168.1.100ipconfig IP02#PSCD ActiveDirectoryAlias:)HKLM:HKCU:Cert:)Env:Variable:)WSMANWsman:)Active Directory(AD:)IIS(IIS:)Remote Desktop Service(RDS:)

PS C:\> Get-PSDrive#3. #Where-Object () Array or WMIWMI or WMICSV Select-Object Hyper-V Hyper-V Hyper-V Hyper-V #PS C:\>get-service | where-object {$_.Status -eq "Running"}1.object

object#PS > Get-Service | Where-Object Status -EQ "Running" | Select-Object Name, Servicetype | Sort-Object ServiceType 123Status Running Name ServiceType ServiceType PS > Get-Service | Where-Object {$_.Status -EQ "Running"} | Select-Object -Property Name, Servicetype | Sort-Object -Property ServiceType V3#TIPS Where-Object#1024Dir | Where-Object {$_.length -GT 1024} `|Select-Object Name,length

#Active Directory aGet-ADUser -Filter * `|Where-Object {$_.name -Like *a*} `| ForEach-Object name

#TIPS PS 3.0 PS C:\>get-service | where-object {$_.Status -eq "Running"}PS C:\>get-service | where-object Status -eq "Running"V3 #2.PS C:\>(Get-Service -Name WSearch).Stop()Windows Search objectWindows SearchPS C:\>Stop-Service WSerarch#TIPS#Dir #Name(dir)[0].Name

#$D = Dir$D[0].Name

#3.PS C:\> Get-NetAdapter | FL Name, InterfaceIndex, MacAddressPS C:\> Get-NetIPAddress -InterfaceIndex 28 -AddressFamily IPv4IP

Format-List #TIPS dir | format-table Name,Lengthdir | format-list Name,Lengthdir | format-wide Name -column 6dir | out-gridview

#4.PS C:\>New-NetIPAddress -InterfaceIndex 24 -IPAddress 192.168.205.102 -AddressFamily IPv4 -PrefixLength 24 -DefaultGateway 192.168.205.254PS C:\> Remove-IPAddress -InterfaceIndex 24 -AddressFamily IPv4IPV4IP PS C:\>Set-DnsClientServerAddress -Interface 24 -ServerAddress 192.168.205.1, 192.168.205.3DNS Set-NetIPAddress PS C:\> Set-DnsClientServerAddress -Interface 24 -ResetServerAddressDNSPS C:\> Set-NetIPInterface -InterfaceIndex 24 -Dhcp EnabledDHCP #5.PS C:\> $Env:ComputerNamePS C:\> (Get-WmiObject -Class Win32_ComputerSystem).NamePS C:\> $New_ClientName = New_ClientNamePS C:\> $SysInfo = Get-WmiObject -Class Win32_ComputerSystemPS C:\> $SysInfo.Rename($New_ClientName)PS C:\> Restart-Computer12C:\> Rename-Computer -NewName tfwin8-xx -Force -Restart WMI #TIPS $FirstName = "Junichi"$LastName = "Anno"$FullName = $FirstName + " " + $LastNameWrite-Output $FullName$arrFullName = $FullName.Split(" ")Write-Output $arrFullname[0]

PS C:\> C:\hogehoge.ps1Junichi AnnoJunichi#TIPS PS > $A = 1PS > $B = 1

PS > $A + $B2PS > $B + $A11

PS > $A = abcPS > $A + $Babc1System.Int32System.String System.Int32 System.String System.String #PS > [System.Int32] $A = 1PS > [System.String] $B = abcPS > [System.Array] $C = , 2012,

PS > $A = 987.654PS > $A988

PS > $A = Hello Cannot convert value "Hello" to type "System.Int32

PS > [System.String] $A = Hello

Int32 0: 1: 20122: [System.String] [System.Int32] [System.String] #PS > [System.Int32] $A = 1PS > Remove-Variable A

PS > Get-Variable | Remove-Variable #TIPS PS >$FirstName = "Junichi"PS >$LastName = "Anno"PS >$FullName = $FirstName $LastName PS >Write-Output $FullNameJunichi AnnoPS >$FullName = $FirstName $LastNamePS >Write-Output $FullName$FirstName $LastName#TIPS PS > $Name = JunichiPS > $Message = Hello $NamePS > $MessageHello JunichiPS > $Name = JunichiPS > $Message = { Hello $Name }PS > $Name = TaroPS > $MessageHello $NamePS > & $MessageHello Taro{} Echo & $Message Name #PS > $Message = { Param( $Name ) Hello $Name }PS > & $Message JunichiHello Junichi#TIPS Array PS > $Users = @()PS > $Users = Junichi, Naoko, KazunoriPS > $Users.Count3PS > $UsersJunichiNaokoKazunoriPS > $Users += MakiPS > $Users += 512PS > $a = { [system.math]::Pow( 2, $N ) } PS > $Users += $aArray {}#Array PS > $Users[3]MakiPS > $Users[-1]PS > $N = 6PS > & $Users[5]64PS > Foreach ($u in $Users) { New-ADUser -Name $u }PS > $Users[2..4]PS > ($Users -eq Kazunori).CountPS > $Users -ne KazunoriPS > $Users -like *M*$users 24Kazunori kazunori M #PS > $arrINT = 1,2,3,4,5,6,7,8,9PS > $arrINT -ge 5PS > $Users += $arrINTPS > $Users | Sort-Object $_ PS > $Users = $Users -ne KazunoriPS > [System.Array]::Reverse($Users)

2Kazunori Users 2#PadLeft / PadRight## $N[] 001 100 PS > $N = @()PS > 001..100 | % { $N += ("$_").Padleft(3,"0")}PS > User$N001002100 PS > $VMs = $N | % {echo VM$_} PS > $VMsVM001VM002VM100#TIPS HashTablePS > $Users = @{}PS > $Users.0001 = JunichiPS > $Users.0001 = JunichiPS > $Users.Add( 0001, Junichi )PS > $Users.Remove(0001)HashTable Array () 1 Junichi 0001 Junichi 0001 #PS > $USDJPY = Import-CSV -Path C:\tools\USDJPY.csv Encoding Default PS > $HT = @{}PS > While ( $i -lt $USDJPY.Count ) {$HT.Add( $USDJPY.[ $i ], $USDJPY.[ $i ] ) ; $i++ }PS > $HT.2012/2/1077.65CSV HashTable #TIPS #cd env:dir

#$env:computername$env:username$env:userdomain$env:SessionName

#6.##PS C:\> $ClientName = ClientNamePS C:\> $Cred = Get-CredentialPS C:\> $New_ClientName = New_ClientNamePS C:\> Rename-Computer -ComputerName $ClientName -LocalCredential $Cred -NewName $New_ClientName -Force -Restart

##PS C:\> $ClientName = ClientNamePS C:\> $Cred = Get-CredentialPS C:\> $New_ClientName = New_ClientNamePS C:\> Rename-Computer -ComputerName $ClientName -DomainCredential $Cred -NewName $New_ClientName -Force -Restart

#PS C:\> $ClientName = ClientNamePS C:\> $Cred = Get-CredentialPS C:\> $New_ClientName = New_ClientNamePS C:\> $SysInfo = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ClientName -Credential $CredPS C:\> $SysInfo.Rename($New_ClientName)

PS C:\> Restart-Computer -ComputerName $ClientName -Credential $cred -Force

WMI ServerClientWMI

#TIPS PS C:\> $Cred = Get-Credential

PS C:\> $user = administratorPS C:\> $pass = ConvertTo-SecureString "P@ssw0rd-AsPlainText -Force PS C:\> $Cred = New-Object System.Management.Automation.PSCredential $user, $pass

#TIPS WMI Testerhttp://technet.microsoft.com/en-us/library/cc782719(v=ws.10)

WMI

#TIPS WMI

0x800706ba0x800410030x80070005

Firewall #Distributed COM Users

wmimgmt.msc

# Firewall Windows Management Instrumentation

#7.PS C:\> $Domain = tf.comPS C:\> $Client = ClientComputerPS C:\> $LocalCred = Get-Credential junichiaPS C:\> $DomainCred = Get-Credential tf\administratorPS C:\> $Admin = tf\administratorPS C:\> $Pass = P@sswordPS C:\> Add-Computer -ComputerName $Clienit -LocalCredential $Cred -Credential $DomainCred -DomainName $Domain -OUPath OU= -Restart -ForceServerAD DomainClientClientWorkgroupClient#PS C:\> $Domain = tf.comPS C:\> $Client = ClientComputerPS C:\> $Cred = Get-Credential junichiaPS C:\> $Admin = tf\administratorPS C:\> $Pass = P@sswordPS C:\> $SysInfo = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ClientComputer -Credential $Cred -Authentication PacketPrivacy PS C:\> $SysInfo.JoinDomainOrWorkgroup($Domain, $Pass, $Admin, OU=xx, 3 )PS C:\> Restart-Computer -ComputerName $Client -Credential $Cred -Force Client connection to WINMGMT needs to be encrypted for this operation. Please adjust your IWbemServices proxy security settings and retry.

1: +2: WMI#8.# $Cred = Get-Credential junichia$Domain = "tf.com"$Admin = "tf\administrator"$Pass = "P@ssword"# SJISUNICODE$InputFile = "C:\Tools\Computers.csv"$OutputFile = "C:\Tools\Computers_unicode.csv"Get-Content $InputFile -Encoding String | Out-File $OutputFile -Encoding unicode# CSV$Computers = Import-Csv -Path $OutputFile -Header ComputerName,IPAddress,Department -Delimiter ","# ForEach ($c in $Computers) { $Client = $c.ComputerName $OU = "OU=" + $c.Department + ",DC=TF,DC=COM $SysInfo = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Client `-Credential $Cred -Authentication PacketPrivacy $SysInfo.JoinDomainOrWorkgroup($Domain, $Pass, $Admin, $OU , 3 ) Restart-Computer -ComputerName $Client -Credential $Cred -Force} ServerCSVClientClienttfwin8-01,192.168.205.101,tfwin8-02,192.168.205.102,123456789101112131415161718192021

#TIPS (`)

copy-item C:\tmp\*.txt `-destination C:\

#TIPS #Write-Output HelloEcho Hello

#$InputData = Read-Host

#Out-File -filepath C:\tmp\list.txt -inputobject $Record

#$file = Get-Content -Path c:\tmp\list.txt$file = type c:\tmp\list.txt

#CSV$file = Import-CSV -Path c:\test.csv#TIPS PS C:\> 1 + 2 + 36PS C:\> Echo Windows PowerShellWindows PowerShellPS C:\> Write-Output 1 + 2 + 31+2+3PS C:\> Echo Windows PowerShellWindowsPowerShell PS C:\> Windows PowerShell

Echo Write-Output AliasPS C:\> 1 + 2 + 3123#TIPS SJIS Get-Content Out-File Unicode

Get-Content -Path $Input -Encoding String | `Out-File -Encoding UNICODE

StringUnicodeByteBigEndianUnicodeUTF8UTF7UTF32AsciiDefaultOem#TIPS Import-CSV 1

-Header -Header 1

ComputerName, IPAddress, Departmenttfwin8-01,192.168.205.101,tfwin8-02,192.168.205.102,$Computers = Import-Csv -Path $OutputFile -Header ComputerName,IPAddress$Computers.IPAddress

#TIPS Out-GridView EXCEL VIEWER

Import-CSV -Path $File | Out-GridView

#TIPS 1#ForEach-Object Get-ADUser -Filter * | ForEach-Object {$_.name} Get-ADUser -Filter * | ForEach-Object name

#foreach$Users = Get-ADUser -Filter * foreach ($user in $Users) { $user.name }

Active Directory name V3#TIPS 2#1101..10

#110 1..10 | % {echo $_ }

#User1 User10 1..10 | % {New-ADUser User$_ }

foreach #TIPS 3$i = 0do { Write-Host $i$i++ }

while ($i -lt 10)

$i = 0do { Write-Host $i$i++ }

until ($i -ge 10)

#9.C:\> Get-EventLog -LogName Security -ComputerName tfdc01 -Newest 1010C:\> Get-EventLog -LogName Security -ComputerName tfdc01 -After 2012/6/1 00:00:00 -Before 2012/6/1 00:10:00IDC:\> Get-EventLog -LogName Security -ComputerName tfdc01 -InstanceID 4632C:\> Get-EventLog -LogName Security -ComputerName tfdc01 -EntryType FailureAudit C:\> Get-EventLog -LogName Security -ComputerName tfdc01 -Message **#C:\> Get-EventLog -LogName Application | Group-Object -Property EntryType -NoElement C:\> Get-EventLog -LogName Application |Group-Object -Property Source,EntryType -NoElement | Select-Object Name,Count #TIPS Select-Object ...PS C:\> $Data = Dir

PS C:\> Select-Object -InputObject $Data -Property Name PS C:\> $Data | Select-Object -Property Name

$data |Select-Object -Unique -Property Name

10$data | Select-Object -Last 10

5$data | Select-Object -First 5#10. C:\> $logFileName = "Security"C:\> $exportFileName = "C:\tmp\" + $logFileName + (get-date -f yyyyMMddhhmmss) + ".evt"C:\> $exportfilenameC:\> $logFile = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.logfilename -eq $logFileName}C:\> $logFile.backupeventlog($exportFileName) EVTPowerShell #11.C:\> New-EventLog -Source "TechFielders" -LogName "TechFielders" TechFielders TechFielders C:\> Write-EventLog -LogName TechFielders -Source TechFielders -EntryType Information -EventId 5963 -Message 1,2,3 " TechFielders #12. param([string] $VMName = "NA", [int] $CPU = 1, [int] $Mem = 10MB)echo -InputObject $VMName, $CPU, $Mem$SwitchName = "Intel(R) 82579LM Gigabit Network Connection - Virtual Switch"New-VM -BootDevice CD ` -MemoryStartupBytes $Mem ` -Name $VMName ` -SwitchName $SwitchName ` -VHDPath \\junichia-vdi\$VMName\$VMName.vhdxSet-VM -ProcessorCount $CPU -DynamicMemory -Name $VMNameAdd-VMNetworkAdapter -VMName $VMName -SwitchName $SwitchNameStart-VM -Name $VMName 1234567891011 PS C:\> .\CreateVirtualMachine.ps1 -VMName VM01" -Mem 1024mb CreateVirtualMachine.ps1#TIPS Write-Output $args[3]

foreach ( $a in $args ) { Write-Output $a }

C:\> .\hogehoge.ps1 My name is Junichi Anno .5MynameisJunichi Anno.Junichi Anno#TIPS param([string] $UserID = ID", [string] $Password =PASS")Write-Output $useridWrite-Output $PasswordC:\> hogehoge.ps1 -userid annoannoPASS#13. Hyper-V $Source = HostSV01$Dist = HostSV02$VMs = get-vm -ComputerName $Source -Name VM*foreach ($VMName in $VMs.Name) { Move-VM -ComputerName $Source -Name $VMName -DestinationHost $Dist }Guest

\\Server\Share\xxx.vhdxSMBGuestSMBHost01Host01

$Source VM OS#14. Do{ $perf =Get-WmiObject -Class win32_perfformatteddata_perfos_processor `-Property PercentProcessorTimeforeach ($p in $perf) { $outrec = "Processor" + $i + ":" + $p.PercentProcessorTime echo $outrec } Start-Sleep -Seconds 1 cls} while (-1)1234567891011111CPUWMI#TIPS

win32_perfformatteddata_perfos_processor

C:\> Get-CimClass Win32_PerfFormatted* |ft CimClassNameC:\> Get-CimClass Win32_PerfRaw* |ft CimClassNameC:\> $PerfMon = Get-CimClass Win32_PerfFormattedData_perfos_processorC:\> $PerfMon.CimClassProperties |ft Name#15.

/C:\> Get-WindowsFeatureC:\> Get-WindowsFeature |Select-Object Name#PS C:\> Add-WindowsFeature -Name User-Interfaces-Infra -IncludeAllSubFeature -IncludeManagementToolsServerCore GUI PS C:\> Add-WindowsFeature Name Server-gui-mgmt-infra -IncludeManagementToolsServerCore (MinShell)#Windows Server 2012 GUI Server CoreMinShellServer W/GUIDesktop ExperienceAvailableAvailableAvailableAvailableWindows PowerShellAvailableAvailableAvailableAvailableNot AvailableAvailableAvailableAvailableMMCNot AvailableAvailableAvailableAvailableNot AvailableNot AvailableAvailableAvailableNot AvailableSome AvailableAvailableAvailableWindows ExplorerNot AvailableNot AvailableAvailableAvailableNot AvailableNot AvailableAvailableAvailableNot AvailableNot AvailableAvailableAvailableInternet ExplorerNot AvailableNot AvailableAvailableAvailableNot AvailableNot AvailableAvailableAvailableNot AvailableNot AvailableNot AvailableAvailableNot AvailableNot AvailableNot AvailableAvailableWinRTNot AvailableNot AvailableNot AvailableAvailableNot AvailableNot AvailableNot AvailableAvailable#159ServerManager PS C:\> Import-Module ServerManagerPS C:\> Get-Command -Module ServerManagerAlias Add-WindowsFeature servermanager Alias Remove-WindowsFeature servermanager Function Disable-ServerManagerStandardUserRemoting servermanager Function Enable-ServerManagerStandardUserRemoting servermanager Cmdlet Get-WindowsFeature servermanager Cmdlet Install-WindowsFeature servermanager Cmdlet Uninstall-WindowsFeature servermanager #16. DC Windows Server 2012 Hyper-V DC02DC03ExportDC01(pdc)PDC Clonable Domain Controllers Hyper-V Windows Server 2012DC Windows Server 2012VHDImportHyper-V Hyper-V #$SourceDC = "DC02"$DistDC = "DC03"$distPDCEmu = DC01"$HyperVHost = ITCAMP-TMP"

Move-ADDirectoryServerOperationMasterRole -Identity $distPDCEmu -OperationMasterRole PDCEmulator

Get-ADComputer $SourceDC | %{Add-ADGroupMember -Identity "Cloneable Domain Controllers" -Members $_.samAccountName}

Invoke-Command -ComputerName $SourceDC -ScriptBlock { Get-ADDCCloningExcludedApplicationList -GenerateXml -Force }

$SB = "New-ADDCCloneConfigFile -Static ` -IPv4Address ""192.168.210.51"" ` -IPv4DNSResolver ""192.168.210.50"" ` -IPv4SubnetMask ""255.255.255.0"" ` -IPv4DefaultGateway ""192.168.210.254"" ` -CloneComputerName " + $DistDC + ` " -SiteName ""Default-First-Site-Name""" Invoke-Command -ComputerName $SourceDC -ScriptBlock { $SB }

Stop-VM $SourceDCPDCDCDCClonable Domain Controllers DC#Get-VM $SourceDC | %{ Export-VM $_ -Path C:\VMs}

Start-VM -Name $SourceDC

$CFG = (Dir C:\VMs\$SourceDC\Virtual Machines\*.xml).FullNamemd E:\$DistDCImport-VM -Path "$CFG" -ComputerName $HyperVHost -GenerateNewId -Copy -VhdDestinationPath E:\$DistDC

Get-VM $SourceDC |Where-Object {$_.State -EQ "Off"} | Rename-VM -NewName $DistDC

Start-VM $DistDCDCDCVMHyper-VOffDCDC#17. $PCName = "itcamp-pc01"Invoke-Command -ComputerName $PCName -ScriptBlock {New-VMSwitch -Name "External" `-AllowManagementOS $True -NetAdapterInterfaceDescription "Intel(R) 82579LM Gigabit Network Connection"}New-VMSwitch -ComputerName $PCName -Name "WS2012Labs-Public" -SwitchType PrivateNew-VMSwitch -ComputerName $PCName -Name "WS2012Labs-CorpNet" -SwitchType PrivateNew-VMSwitch -ComputerName $PCName -Name "WS2012Labs-Storage" -SwitchType PrivateNew-VMSwitch -ComputerName $PCName -Name "WS2012Labs-Internet" -SwitchType PrivateNew-VMSwitch -ComputerName $PCName -Name "WS2012Labs-HA" -SwitchType Private

#18. Workflow RemoveFOCsWF {

$PCs = Import-Csv -Path pclist.txt -Header "PC","IP"

foreach -Parallel ($pc in $PCs) { Write-Output -InputObject $pc.pc Remove-WindowsFeature -ComputerName $pc.pc Failover-Clustering -IncludeManagementTools -Restart }}

RemoveFOCsWF itcamp-pc01,192.168.210.1itcamp-pc02,192.168.210.2itcamp-pc03,192.168.210.3itcamp-pc04,192.168.210.4itcamp-pc05,192.168.210.5itcamp-pc06,192.168.210.6 #19. Workflow RestartAllPCsWF {

$PCs = Import-Csv -Path pclist.txt -Header "PC","IP"

foreach -Parallel ($pc in $PCs) {

Write-Output -InputObject $pc.pc ##Restart-Computer -PSComputerName $pc.PC -Force Stop-Computer -PSComputerName $pc.PC -Force }}

RestartAllPCsWF itcamp-pc01,192.168.210.1itcamp-pc02,192.168.210.2itcamp-pc03,192.168.210.3itcamp-pc04,192.168.210.4itcamp-pc05,192.168.210.5itcamp-pc06,192.168.210.6 #20. Hyper-V Workflow StopAllVMs {

$PCs = Import-Csv -Path pclist.txt -Header "PC","IP"

foreach -Parallel ($pc in $PCs){

##Get-VM -ComputerName $pc.pc |Start-VM Get-VM -ComputerName $pc.pc |Stop-VM -Force }

}itcamp-pc01,192.168.210.1itcamp-pc02,192.168.210.2itcamp-pc03,192.168.210.3itcamp-pc04,192.168.210.4itcamp-pc05,192.168.210.5itcamp-pc06,192.168.210.6 #21. Hyper-V Workflow DisableMigrationWF {

$PCs = Import-Csv -Path c:\tools\ps\HOLSetup\pclist.txt -Header "PC","IP"

foreach -Parallel ($pc in $PCs) {

##Disable-VMMigration -ComputerName $pc.pc ##Set-VMHost -ComputerName $pc.pc -VirtualMachineMigrationAuthenticationType CredSSP `-MaximumVirtualMachineMigrations 2 -UseAnyNetworkForMigration $true

Enable-VMMigration -ComputerName $pc.pc Set-VMHost -ComputerName $pc.pc -VirtualMachineMigrationAuthenticationType Kerberos `-MaximumVirtualMachineMigrations 2 -UseAnyNetworkForMigration $True }}

DisableMigrationWFitcamp-pc01,192.168.210.1itcamp-pc02,192.168.210.2itcamp-pc03,192.168.210.3itcamp-pc04,192.168.210.4itcamp-pc05,192.168.210.5itcamp-pc06,192.168.210.6 #5. Tips#True False $True False C:\> $MyNameIsJunichi = $TrueC:\> If ($MyNameIsJunichi -eq $True) {Echo 1}1

#Date DateDayDayOfWeekDayOfYearHourKindMillisecondMinuteMonthSecondTicksTimeOfDayYearDateTime

AddAddDaysAddHoursAddMillisecondsAddMinutesAddMonthsAddSecondsAddTicksAddYearsCompareToEqualsGetDateTimeFormatsGetHashCodeGetTypeGetTypeCodeIsDaylightSavingTimeSubtractToBinaryToFileTimeToFileTimeUtcToLocalTimeToLongDateStringToLongTimeStringToOADateToShortDateStringToShortTimeStringToStringToUniversalTime

PS C:\> (Date).Year2012PS C:\> (date).adddays(10)24 5 23 12:49:10 #unix ls get-ChildItemcp copy-Object grep select-Stringsort sort-Objectman helpclear clear-Hostcat get-Contentkill stop-Processtee tee-Objecttail get-Content

Get-Alias tail #Get-Content Tail ## gc .\test.txt -wait -tail 0## 510(gc .\test.txt)[4..9]## 5gc .\test.txt -totalcount 5## 5 gc .\test.txt | Select-Object -Last 5 tail gc .\test.txt -tail 5## gc .\test.txt -wait | Select-String -Pattern ^a #tail Get-Content Alias Set-Alias tail Get-ContentAdd-Content $profile "Set-Alias tail get-content" -Force#Part 2 #Agenda PS PS PS PS Windows PowerShell Web Access

#6. #OS PC PS C:\>Enable-PSRemoting forceWinRMWindows FirewallListener

Windows Managementport 5985#Enable-PSRemoting PowerShell 3.0 Windows Server ADDCDCWindows Client WinRM WinRM WinRM WinRM WinRM SkipNetworkProfileCheck Firewall Set-NetFirewallRule -Name WINRM-HTTP-In-TCP-PUBLIC -RemoteAddres Anyhttp://technet.microsoft.com/en-us/library/hh849694.aspx#

[]-[]-[]-[Windows ][Windows (WinRM)]

WinRM #WinRM

#Windows Firewall WinRM

[]-[]-[Windows ]-[][Windows][ Windows (-------)][]

#

#

IPIP#PS C:\> cd WSMan:PS WSMan:\> cd localhost\Listner\Listener_1084132640PS WSMan:\localhost\Listener\Listener_1084132640> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Listener\Listener_1084132640

Type Name SourceOfValue Value ---- ---- ------------- ----- System.String Address * System.String Transport HTTP System.String Port 5985 System.String Hostname System.String Enabled true System.String URLPrefix wsman System.String CertificateThumbprint System.String ListeningOn_1038621592 10.168.133.49 System.String ListeningOn_1770022257 127.0.0.1 System.String ListeningOn_1055432771 192.168.205.1 System.String ListeningOn_1414502903 ::1 System.String ListeningOn_894013609 2001:4898:0:fff:0:5e...System.String ListeningOn_1270366863 fe80::5efe:10.168.13...System.String ListeningOn_1565265845 fe80::5efe:192.168.2...System.String ListeningOn_2078661606 fe80::25a7:4656:665e...System.String ListeningOn_1147683958 fe80::fc39:ec3b:d823...

PS WSMan:\localhost\Listener\Listener_1084132640> Listener #TrustedHostActive Directory Or orActive Directory OSCredential WinRMWindows FirewallLitener

Windows ManagementTrustedHosts#PS C:\> Get-Item wsman:\localhost\Client\TrustedHosts

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type Name SourceOfValue Value ---- ---- ------------- ----- System.String TrustedHosts

PS C:\> Set-Item wsman:\localhost\Client\TrustedHosts 192.168.205.* -Concatenate

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type Name SourceOfValue Value ---- ---- ------------- ----- System.String TrustedHosts 192.168.205.*

#TIPSNIC

Windows Windows 7/8 PC Server Enable-PSRemoting -Force -SkipNetworkProfileCheck

#7. -ComputerName #3 -ComputerName -ComputerName PSEnter-PSSession -ComputerName SSH Exit Invoke-Command -ComputerName -ComputerName #-ComputerName PS C:\> Get-Command -CommandType Cmdlet -ParameterName ComputerName Invoke-Command New-PSSession Connect-PSSession Receive-PSSession Get-PSSession Remove-PSSession Receive-Job Enter-PSSession Add-Computer Clear-EventLog Get-EventLog Get-HotFix Get-Process Get-Service Get-WmiObject Invoke-WmiMethod Limit-EventLog New-EventLog Register-WmiEvent Remove-Computer Remove-EventLog Remove-WmiObject Rename-Computer Restart-Computer Set-Service Set-WmiInstance Show-EventLog Stop-Computer Test-Connection Write-EventLog Get-WindowsFeature Install-WindowsFeature Uninstall-WindowsFeature #-ComputerName PS C:\> Get-EventLog -ComputerName tfdc02 -LogName Security -Newest 10 PS C:\> Restart-Computer -ComputerName tfsv02 PS C:\> get-WindowsFeature -ComputerName tfsv02 /PS C:\> Add-WindowsFeature -ComputerName tfsv02 -Name RSAT-Hyper-V-Tools -IncludeAllSubFeature -IncludeManagementTools Hyper-V #8. PS # 3 -ComputerName -ComputerName PSEnter-PSSession -ComputerName SSH Exit Invoke-Command -ComputerName -ComputerName # PS Local Computer

Remote ComputerPSPSRemote ComputerPSPSPSPowerShell.exe PSWindows PowerShell CALLCALLCALLCALL#PS SourceTargetPS PS -ComputerName Re-usable PS #Invoke-Command -ComputerName -ComputerName Start-Service, Stop-Service DOS netstat gpupdate

-Credential -Credential

-FilePath OK

#Invoke-Command PS C:\> Invoke-Command -ComputerName tfsv02 -ScriptBlock{ Get-Service } PS C:\>Invoke-Command -ComputerName tfsv02 -ScriptBlock{ Stop-Service -Name wuauserv } Windows Update PS C:\>Invoke-Command -ComputerName tfsv02 -ScriptBlock{ GPUpdate.exe } GPUpdate PS C:\> Invoke-Command -ComputerName tfsv02 -ScriptBlock{ cd env: ; dir } Get-Service -ComputerName #Invoke-Command -FilePath -FilePath .ps1Invoke-Command -ComputerName SV01 -FilePath .\hogehoge.ps1Invoke-Command -ComputerName SV01 -ScriptBlock {.\hogehoge.ps1}Target Computerhogehoge.ps1Get-ServiceTarget Computerhogehoge.ps1#param([string] $VMName = "VM01", [int] $CPU = 1, [int] $Mem = 10MB)Stop-VM -Name $VMName -ForceRemove-VM -Name $VMName -ForceRemove-Item -Path \\junichia-vdi\VMs\$VMName -Recurse -Force$SwitchName = "Intel(R) 82579LM Gigabit Network Connection - Virtual Switch"New-VM -BootDevice CD ` -MemoryStartupBytes $Mem ` -Name $VMName ` -SwitchName $SwitchName ` -NewVHDPath \\junichia-vdi\VMs\$VMName\$VMName.vhdx ` -NewVHDSizeBytes 40GBSet-VM -ProcessorCount $CPU -DynamicMemory -Name $VMNameAdd-VMNetworkAdapter -VMName $VMName -SwitchName $SwitchNameStart-VM -Name $VMName 1234567891011121314

PS C:\> Invoke-Command -ComputerName "junichia-demo05" -FilePath ".\CreateVirtualMachine.ps1" -ArgumentList Guest99",2",1024MB" CreateVirtualMachine.ps1#Invoke-Command PS Invoke-Command PS> Invoke-Command -ComputerName Server1 -ScriptBlock {$A = 1}PS> Invoke-Command -ComputerName Server1 -ScriptBlock {$B = 1} PS> Invoke-Command -ComputerName Server1 -ScriptBlock {$C = $A + $B}PS> Invoke-Command -ComputerName Server1 -ScriptBlock {$A=1; $B=2 ; $C=$A+$B }#PS > $ComputerList = tfdc01, tfdc02PS > Get-Service -ComputerName $ComputerList | Sort-Object MachineName, Name | Select-Object MachineName, Name, Status PS > $ComputerList = tfdc01, tfdc02PS > Invoke-Command -ComputerName $ComputerList {Get-Service |Sort-Object PSComupterName, Name | Select-Object PSComputerName, Name, Status} | FT32-ComuterName MachineName PSComputerName #$PSComputerNameGet-Service -ComputerName TARGETInvoke-Command -ComputerName TARGET { Get-Service }SourceTargetWMISourceTargetWMIGet-Service MachineNameGet-Service MachineName.Target $PSComputerName PSSession #CSVInvoke-Command -ComputerName (Import-CSV computerlist.txt).HostName {get-culture}

LCID Name DisplayName PSComputerName---- ---- ----------- --------------1041 ja-JP ue (u) tfdc01 ja-JP ue (u) tfdc02 ja-JP ue (u) tfsv021041 ja-JP ue (u) tfsv01 HostName,IPAddresstfdc01,192.168.1.1tfdc02,192.168.1.2tfsv01,192.168.1.3tfsv02,192.168.1.4 #Enter-PSSessionPS> Enter-PSSession -ComputerName Server1[Server1]: PS > $A = 1[Server1]: PS > $B = 2[Server1]: PS > $C = $A + $BPS> Exit-PSSession#9. PS # PS PS > $S = New-PSSession -ComputerName CL01PS > Invoke-Command -session $S -ScriptBlock {$A=1}PS > Invoke-Command -session $S -ScriptBlock {$B=2}PS > Invoke-Command -session $S -ScriptBlock {$C=$A+$B}PS > Enter-PSSession $S[CL01] PS > Echo $C[CL01] 3PS > Exit-PSSessionPS > Remove-Session $S

New-PSSessionRemove-PSSessionGet-PSSessionConnect-PSSession#PS > $S = New-PSSession -ComputerName CL01,CL02PS > $S

Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 80 Session80 tfdc01 Opened Microsoft.PowerShell Available 81 Session81 tfdc02 Opened Microsoft.PowerShell Available

PS > Invoke-Command -Session $S {Get-Culture}Target1Target2Source#PS$Using:PS C:\> $S = New-PSSession -ComputerName tfdc01PS C:\> $MyName = Junichi AnnoPS C:\> Invoke-Command -Session $S {Echo $Using:MyName}

Junichi Anno#PS Get-PSSessionTarget1Source1Source2Get-PSSession PS C:\tools\ps> Get-PSSession -ComputerName Target1

Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 65 tfdc01_Session target1 Opened Microsoft.PowerShell Available 80 Session80 taeget1 Opened Microsoft.PowerShell Available109 Session109 target1 Opened Microsoft.PowerShell Available Credential -Credential #PS Target1Source1Source2 PS State=Disconnected, Availability=None Disconnect-PSSession Disconnect PC Disconnected 2State=DisconnectedAvailability=NoneDisconnect-PSSessionConnect-PSSession#PS > $S = New-PSSession -ComputerName Target1PS > $Result = Invoke-Command -Session $S {Get-Service}PS > Disconnect-PSSession -Session $S

Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------121 Session121 Target1 Disconnected Microsoft.PowerShell NoneTargetPC1PC2PS > Get-PSSession -ComputerName Target1 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------10 Session112 tfdc01 Disconnected Microsoft.PowerShell Busy12 Session121 tfdc01 Disconnected Microsoft.PowerShell None

PS > $S = Get-PSSession -Name Session121 -ComputerName Target1PS > Connect-PSSession -Session $S#State AvailabilityAvailabilityStateOpenedDisconnectedNoneBusyAvailableId Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------10 Session112 tfdc01 Disconnected Microsoft.PowerShell Busy12 Session121 tfdc01 Disconnected Microsoft.PowerShell None# PC ......Id Name ComputerName State ConfigurationName Availability-- ---- ------------ ----- ----------------- ------------10 Session112 tfdc01 Disconnected Microsoft.PowerShell BusyAvailability Busy 2Id Name ComputerName State ConfigurationName Availability-- ---- ------------ ----- ----------------- ------------10 Session112 tfdc01 Disconnected Microsoft.PowerShell None#PS PS Remove-PSSession

Disconnect PS > Remove-PSSession -Session $SPS C:\> Get-PSSessionConfiguration | ft name,idletimeoutms,maxidletimeoutms

Name IdleTimeoutms MaxIdleTimeoutms ---- ------------- ---------------- microsoft.powershell 7200000 2147483647microsoft.powershell.workflow 7200000 2147483647microsoft.powershell32 7200000 2147483647microsoft.windows.servermanagerworkflows 180000 180000

2596#PS C:\> $SessionOption = New-PSSessionOption -IdleTimeOutMSec 60000PS C:\> $S = New-PSSession -ComputerName Target1 -SessionOption $SessionOptionRegister-PSSessionConfiguration -TransportOption Set-PSSessionConfiguration -TransportOption PS New-PSSession -SessionOption Invoke-Command -SessionOption PS Disconnect-PSSession -IdeleTimeOutSec #FULLBlock : ClearDropPS C\> Get-PSSessionConfiguration | ft Name, OutputBufferingModeName OutputBufferingMode---- ------------------- microsoft.powershell Blockmicrosoft.powershell.workflow Blockmicrosoft.powershell32 Blockmicrosoft.windows.servermanagerworkflows Block PS Drop PS C:\> $o = New-PSSessionOption -OutputBufferingMode DropPS C:\> New-PSSession -SessionOption $o#Source2 PS LOCALHOST PS PS > $S = Get-PSSession -ComputerName localhost -Name BackupPS > Receive-PSSession -Session $SPS > Remove-PSSession -Session $S Source1/TargetConnect-PSSessionPS> $S = New-PSSession -Name BackupPS> Invoke-Command -Session $S -FilePath backup.ps1 -AsJobPS> Disconnect-PSSession -Session $S#Invoke-Command -Session PS C:> $s = New-PSSession -ComputerName Server1PS C:> Import-PSSession -Session $s -Module HYPER-VPS C:\> Get-VM |ft name

Name ---- VM01VM02VM03VM04VM05Windows Serverw/ Hyper-V

PS SessionHyper-V Module#10. PSWA#PSWS

Windows PowerShell Web AccessServer

PCSessionPS SessionWS-Man PS SessionIntranetDMZInternetHomeDevices

#221PowerShell Web Access

PowerShell Web Access #

IIS SSL

#PowerShell PS C:\> Set-ExecutionPolicy RemoteSignedPS C:\> Import-Module PowerShellWebAccessPS C:\> Install-PswaWebApplication -webSiteName "Default Web Site" PS C:\> Add-PswaAuthorizationRule * * * https:///pswa

#Part 3 #Windows PowerShell 2.0 get-eventlog Security-AsJob Start-Job #-AsJob-AsJob PS C:\> Get-Command -ParameterName asjob

CommandType Name ModuleName ----------- ---- ---------- Function Get-SMCounterSample ServerManagerTasks Function Get-SMPerformanceCollector ServerManagerTasks Function Get-SMServerBpaResult ServerManagerTasks Function Get-SMServerClusterName ServerManagerTasks Function Get-SMServerEvent ServerManagerTasks Function Get-SMServerFeature ServerManagerTasks Function Get-SMServerInventory ServerManagerTasks Function Get-SMServerService ServerManagerTasks Function Remove-SMServerPerformanceLog ServerManagerTasks Function Start-SMPerformanceCollector ServerManagerTasks Function Stop-SMPerformanceCollector ServerManagerTasks Cmdlet Get-WmiObject Microsoft.PowerShell.Management Cmdlet Invoke-Command Microsoft.PowerShell.Core Cmdlet Invoke-WmiMethod Microsoft.PowerShell.Management Cmdlet Remove-WmiObject Microsoft.PowerShell.Management Cmdlet Restart-Computer Microsoft.PowerShell.Management Cmdlet Set-WmiInstance Microsoft.PowerShell.Management Cmdlet Stop-Computer Microsoft.PowerShell.Management Cmdlet Test-Connection Microsoft.PowerShell.ManagementAsJob#Get-JobReceive-JobRemove-JobStart-JobStop-JobWait-Job#PS C:\> $job = start-job -scriptblock {do {$a = 0; echo (date) ; start-sleep 5} while ($a -eq 0) }PS C:\> $job

Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 6 Job6 Completed True localhost get-eventlog "Windows ...

PS C:\> Receive-Job $job -KeepPS C:\> Stop-Job $jobPS C:\> Remove-job $job

start-job -scriptblock { }-Keep 51#$flg = $true$index = 0$index_old = 0Do{ $Eventlog = Get-Eventlog -LogName TechFielders -Source TechFielders $index = $eventlog | Select-Object -First 1 -Property Index $delta_index = $index.Index - $index_old if ($delta_index -gt 0) { $eventlog | `Select-Object -First $delta_index | `Sort-Object -Property Index } Start-Sleep -Seconds 1 $index_old = $index.Index} While ($flg) 1234567891011121314WatchNewEventLog.ps1 Index ###PS C:\> Start-Job -FilePath .\WatchNewEventLog.ps1 -Name WatchNewEventLog

Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 4 WatchNewEven... BackgroundJob Running True localhost $flg = $true...

## PS C:\> Receive-Job -Name WatchNewEventLog

Index Time EntryType Source InstanceID Message ----- ---- --------- ------ ---------- ------- 1 6 02 17:41 Information TechFielders 5963 2 6 02 18:09 Information techfielders 99 3 6 02 18:11 Information TechFielders 9909 4 6 02 18:12 Information TechFielders 9909 5 6 02 18:13 Information TechFielders 9909 6 6 02 18:13 Information TechFielders 9909 Hello C:\> Write-EventLog -LogName TechFielders -Message "Hello" -Source "TechFielders" -EventId 5963 #TargetSourceSessionCmdLetJob/ResultTargetSourceSessionCmdLetJob/Result#PS> Invoke-Command -Session $S -FilePath backup.ps1 -AsJob

Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 2 Job2 RemoteJob Completed True tfdc01 get-service

PS> Receive-Job -Id 2SRCTarget1Invoke-Command -AsJob !!Invoke-Command Invoke-Command !!!!!#PS> $S = New-PSSession -ComputerName Target -Name BackupPS> $Script = .\testscript.ps1"PS> Invoke-Command -Session $S { Start-Job -FilePath $Script }

Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost backup...

PS> Disconnect-PSSession -Session $SSRC1 Target2Invoke-Command {Start-Job} SRC2#PS> Get-PSSession -ComputerName tfdc01

Id Name ComputerName State ConfigurationName Availability-- ---- ------------ ----- ----------------- ------------- 1 backup tfdc01 Disconnected Microsoft.PowerShell None

PS> $S = Connect-PSSession -Name backup -ComputerName tfdc01PS> Invoke-Command -Session $S { Get-Job }

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 1 Job1 BackgroundJob Completed True localhost

PS> Invoke-Command -Session $S {Receive-Job -Id 1}

#Add-JobTrigger Disable-JobTrigger Disable-ScheduledJob Enable-JobTrigger Enable-ScheduledJob Get-JobTrigger Get-ScheduledJob Get-ScheduledJobOptionNew-JobTrigger New-ScheduledJobOption Register-ScheduledJob Remove-JobTrigger Set-JobTrigger Set-ScheduledJob Set-ScheduledJobOption Unregister-ScheduledJob PSScheduledJob

#

$trigger = New-JobTrigger -Daily -At 3amRegister-ScheduledJob -Name EnergyAnalysisJob -Trigger $trigger -ScriptBlock {powercfg.exe -energy -xml -output C:\temp\energy.xml -duration 60 | Out-Null$EnergyReport = [xml](get-content C:\temp\energy.xml)$namespace = @{ ns = "http://schemas.microsoft.com/energy/2007" }$xPath = "//ns:EnergyReport/ns:Troubleshooter/ns:AnalysisLog/ns:LogEntry[ns:Severity = 'Error']"$EnergyErrors = $EnergyReport | Select-Xml -XPath $xPath -Namespace $namespace $EnergyErrors.Node | select Name, Description} #Part 4 #Agenda Windows PowerShell Workflow Windows PowerShell Workflow

#12. Windows PowerShell Workflow #

#UserList#PowerShell 3.0 - WF

WF12checkpoint1checkpoint3WF12

#PowerShell Suspend PC PC 1XAML Windows PowerShell 3.0 #13. Windows PowerShell Workflow ##Wokflow PowerShell ISE workflow workflow ( ) {}workflow MyWorkflow ( [String] $ServiceName ){

Get-Service -PSComputerName $PSComputerName -Name $ServiceName

}MyWorkflow -ComputerName #Workflow .ps1 PowerShell ISE

#Workflow PCManagedNodeWFPCManagedNodeWF WFWinRMWinRMWMIWMIIn-Process Execution!Execution in Workflow Configuration :)#Workflow In-process

Activity PowerShell

Workflow

Activity Workflow PS WinRM #In-Process LocalhostPowershell.exeActivity Host ProcessActivity Host Managed NodePowerShell Remoting(RSRP) Managed NodeCIMOM/WMI

PSWFExecutive

PSWFCmdlets#Workflow Managed NodePowerShell Remoting(RSRP) Managed NodeCIMOM/WMI

PowerShell WorkflowActivity Host ProcessActivity HostPSWFExecutiveClientPSJobProxy/PSJob API/PSRPWinRMClientWinRMService#Proxy NodePCWFManagedNodeWinRMWMIManagedNodeWinRMWMIManagedNodeWinRMWMIWinRMPS C:\> $S = New-PSWorkflowSession -ComputerName PS C:\> Invoke-Command Session $S -FilePath mywf.ps1PS1PS C:\> $S = New-PSWorkflowSession -ComputerName PS C:\> Invoke-Command Session $S { .\mywf.ps1 }PS1# PS PS C:\> Invoke-Command -ComputerName NODE -FilePath .\mywf.ps12PS C:\> $S = New-PSSession -ComputerName NODEPS C:\> Invoke-Command -Session $S -FilePath .\mywf.ps1PS WFPS C:\>.\mywf.ps11 orz...PS C:\> Invoke-Command -ComputerName NODE -FilePath .\mywf.ps1 -asjob#workflow ...AST(abstract syntax tree)workflow{ Get-Service}.ps1 workflow Script-to-workflow XAMLworkflowActivity TreeWorkflow Foundation 4ActivityXamlService Class#Get-Command PS C:\> Get-Command PS C:\> Get-Command MyWorkflow

CommandType Name ModuleName----------- ---- ----------Workflow MyWorkflow#PS C:\> Get-Command MyWorkflow |Get-Member TypeName: System.Management.Automation.WorkflowInfo

Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ResolveParameter Method System.Management.Automation.ParameterMetada...ToString Method string ToString() CmdletBinding Property bool CmdletBinding {get;} RemotingCapability Property System.Management.Automation.RemotingCapabil...ScriptBlock Property scriptblock ScriptBlock {get;} Verb Property string Verb {get;} Visibility Property System.Management.Automation.SessionStateEnt...WorkflowsCalled Property System.Collections.ObjectModel.ReadOnlyColle...XamlDefinition Property string XamlDefinition {get;} HelpUri ScriptProperty System.Object HelpUri {get=$oldProgressPrefe...

#XAML PS C:\> (Get-Command MyWorkflow).XamlDefinition

Position #

PS C:\> MyWorkflow#-AsJob SRCTargetStart-Job SRC1 TargetSRC2Invoke-Command Session $S { ..... } -AsJob Invoke-Command { Start-Job } #PSWorkflowSession ManagedNode ManagedNode ManagedNode ManagedNode1PSWorkflowSessionPC2PC1Invoke-Command Session $S { WorkflowName -AsJob }#Workflow

Workflow Workflow

Workflow

C:\> $S = New-PSWorkflowSession -ComputerName PROXYNODEC:\>Invoke-Command $S { MyWorkflow -ServiceName WinRM -PSComputerName TARGET1,TARGET2,TARGET3 -AsJob }workflow MyWorkflow ( [String] $ServiceName ){Get-Service -PSComputerName $PSComputerName -Name $ServiceName}-PSComputerName C:\> Disconnect-PSSession $S#New-PSWorkflowSession New-PSSession PS PS C:\> (New-PSworkflowSession).ConfigurationNameMicrosoft.PowerShell.Workflow

PS C:\> Get-PSSessionConfiguration Microsoft.PowerShell.WorkflowName : microsoft.powershell.workflowPSVersion : 3.0StartupScript : RunAsUser : Permission : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed

PS C:\> (New-PSSession).ConfigurationNameMicrosoft.PowerShell

PS C:\> Get-PSSessionConfiguration Microsoft.PowerShellName : microsoft.powershellPSVersion : 3.0StartupScript : RunAsUser : Permission : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed#PSWorkflow Windows PowerShell WorkFlow 2New-PSWorkflowSession PS New-PSWorkflowExecutionOption#Get-WmiObject -Class Win32_ComputerSystem -PSComputerName TARGET01 -PSCredential $PSCredentials Get-WmiObject -Class Win32_ComputerSystem -ComputerName TARGET01-Credential $PSCredentials PS Workflow#C:\>MyWorkflow -PSComputerName SV01,SV02,SV03,SV04 -PSCredential tf\administratorworkflow MyWorkflow{Get-WmiObject -Class Win32_ComputerSystem -PSComputerName $PSComputerName -PSCredential $PSCredential}#PS PSParameterCollectionPSComputerNamePSCredentialPSConnectionRetryCountPSConnectionRetryIntervalSecPSRunningTimeoutSecPSPersist$True $FalsePSAuthenticationDefault / None / Connect / Call / Packet / PacketIntegrity / PacketPrivacyPSApplicationNameURI WSMANPSPort5985WinRM for HTTP5986WinRM for HTTPS#PSUseSSLSSLPSConfigurationName Microsoft.PowerShellPSConnectionURI http://localhost:5985/WSMANPSAllowRedirectionURIPowerShell $FalsePSSessionOptionNew-PSSessionOption PSCertificateThumbprintX.509PSPrivateMetadataAsJob*-jobJobNameAsJob Job InputObject#PS C:\> Invoke-Command -Session $S { Get-Job }

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 1 Job1 PSWorkflowJob Completed True tfdc02,tfsv01,tfsv02

PS C:\> Invoke-Command -Session $S { Receive-Job -Id 1 -Keep }

Status Name DisplayName PSComputerName ------ ---- ----------- -------------- Running WinRM Windows Remote Management (WS-Manag... tfdc01 Running WinRM Windows Remote Management (WS-Manag... tfdc01 Running WinRM Windows Remote Management (WS-Manag... tfdc01

#...JOB PS C:\> $JOB = Invoke-Command -Session $S { Get-Job }PS C:\> $JOB

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 1 Job1 PSWorkflowJob Completed True tfdc02,tfsv01,tf...

PS C:\> $JOB.ChildJobs

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 2 Job2 PSWorkflowJob Completed True tfdc02 3 Job3 PSWorkflowJob Completed True tfsv01 4 Job4 PSWorkflowJob Completed True tfsv03

Deserialized.System.Management.Automation.ContainerParentJob Deserialized.Microsoft.PowerShell.Workflow.PSWorkflowJob LocationChildJob JOB# PS C:\> $JOB |Get-Member

TypeName: Deserialized.System.Management.Automation.ContainerParentJob

Name MemberType Definition ---- ---------- ---------- ToString Method string ToString(), string ToString(string format, System.IFor...PSComputerName NoteProperty System.String PSComputerName=tfdc01 PSShowComputerName NoteProperty System.Boolean PSShowComputerName=True RunspaceId NoteProperty System.Guid RunspaceId=ebcb1d6d-60b6-460b-b2b4-23a065bab884 State NoteProperty System.String State=Completed ChildJobs Property Deserialized.System.Collections.Generic.List`1[[System.Manage...Command Property System.String {get;set;} HasMoreData Property System.Boolean {get;set;} Id Property System.Int32 {get;set;} InstanceId Property System.Guid {get;set;} JobStateInfo Property System.Management.Automation.JobStateInfo {get;set;} Location Property System.String {get;set;} Name Property System.String {get;set;} PSBeginTime Property System.DateTime {get;set;} PSEndTime Property System.DateTime {get;set;} PSJobTypeName Property System.String {get;set;} StatusMessage Property System.String {get;set;}#PS C:\> Invoke-Command -Session $S {Get-Job -IncludeChildJob}

Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------1 Job1 PSWorkflowJob Completed False tfdc02,tfsv01,tfsv03 myw...2 Job2 PSWorkflowJob Completed False tfdc02 MyW...3 Job3 PSWorkflowJob Completed False tfsv01 MyW...4 Job4 PSWorkflowJob Completed False tfsv03 MyW... PS C:\> Invoke-Command -Session $S {Receive-Job -Job (Get-Job -Id 4) -Keep}

PS C:\> Invoke-Command -Session $S {Receive-Job -Job (Get-Job) -Location tfsv02 -Keep } #14. Windows PowerShell Workflow #workflow MyWorkflow { Start-Sleep -Second 1 Get-Date Start-Sleep -Second 1 Get-Date Start-Sleep -Second 1 Get-Date}PS C:\> MyWorkflow

2012618 18:35:002012618 18:35:012012618 18:35:02

PS C:\> # workflow MyWorkflow{ Start-Sleep -Second 1 Echo -InputObject "$PSComputerName $(Get-Date)" Start-Sleep -Second 1 Echo -InputObject "$PSComputerName $(Get-Date)" Start-Sleep -Second 1 Echo -InputObject "$PSComputerName $(Get-Date)"} PS C:\> MyWorkflow -PSComputerName tfsv01,tfsv02tfsv01 06/18/2012 18:43:58tfsv02 06/18/2012 18:43:58tfsv01 06/18/2012 18:43:59tfsc02 06/18/2012 18:43:59tfsv01 06/18/2012 18:44:00tfsv02 06/18/2012 18:44:00 # workflow MyWorkflow{ Get-Date parallel{ Start-Sleep -Second 1 Echo -InputObject "1 $PSComputerName $(Get-Date)" Start-Sleep -Second 1 Echo -InputObject "2 $PSComputerName $(Get-Date)" Start-Sleep -Second 1 Echo -InputObject "3 $PSComputerName $(Get-Date)" } Get-Date} #PS C:\> MyWorkflow -PSComputerName tfsv01

2012618 18:50:581 tfsv01 06/18/2012 18:50:582 tfsv01 06/18/2012 18:50:583 tfsv01 06/18/2012 18:50:582012618 18:50:59 # workflow MyWorkflow{ Get-Date parallel{ Echo -InputObject "1 $PSComputerName $(Get-Date)" Start-Sleep -Second 1 Sequence{ Start-Sleep -Second 1 Echo -InputObject "2 $PSComputerName $(Get-Date)" Start-Sleep -Second 1 } Echo -InputObject "3 $PSComputerName $(Get-Date)" Start-Sleep -Second 1 } Get-Date} #Workflow JoinDomain ([string] $Domain){Add-Computer -PSComputerName $PSComputerName -DomainName $Domain Credential $PSCredentialRestart-Computer -PSComputerName $PSComputerName -Wait ` -For PowerShell -Force} PS C:\> $Clients = Import-Csv -Path C:\tools\ps\wf\Clientlist.txtPS C:\> $Cred = Contoso\administrator PS C:\> JoinDomain -Domain CONTOSO -PSComputerName $Clients.ComputerName -PSCredential $Cred ComputerNameClient01Client02Client03Client04Client05 #foreach -parallelworkflow JoinDomain2( [string[]] $ClientList){ $Clients = Import-Csv -Path $ClientList foreach -Parallel ($Client in $Clients.ComputerName) { Add-Computer -PSComputerName $PSComputerName `-DomainName $Domain Credential $PSCredential Restart-Computer -PSComputerName $Client -Wait -For Wmi -Force Get-WmiObject -Class Win32_ComputerSystem -PSComputerName $Client Echo -InputObject $Status.Domain }} ComputerNameClient01Client02Client03Client04Client05 PS C:\> JoinDomain -Domain CONTOSO -ClientList .\ClientList.txt -PSCredential $Cred 1#1000 workflow CreateNewUser([string[]] $IDs){ foreach -parallel($ID in $IDs) {New-ADUser -Name user$ID -PasswordNeverExpires $true }} #15. #PSWorkflowJob Remove-Job PS C:\tools\ps\wf> Invoke-Command -Session $S { Get-Job }

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 1 Job1 PSWorkflowJob Running True localhost 14 Job7 PSWorkflowJob Completed True tfsv01,tfdc02,tf...15 Job3 PSWorkflowJob Suspended True localhost 16 Job1 PSWorkflowJob Completed True tfsv03,tfsv01,tf...17 Job15 PSWorkflowJob Stopped True localhost 18 Job1 PSWorkflowJob Suspended True localhost 19 Job1 PSWorkflowJob Completed True localhost 20 Job41 PSWorkflowJob Suspended True localhost Invoke-Command -Session $S { Get-Job | Stop-Job} Invoke-Command -Session $S { Get-Job | Remove-Job }Stopped #Checkpoint-Workflow Workflow PersistResult { $I =0 Do { $I ++ Echo -Input "$I :: $(get-date)" Checkpoint-Workflow Start-Sleep -second 10 $I ++ Echo -Input "$I ** $(get-date)" Start-Sleep -second 10 } While (-1)} -PSPersist $true # PS C:\tools\ps\wf> Invoke-Command -Session $s {Resume-Job 2}

Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 2 Job3 PSWorkflowJob Suspended True localhost

PS C:\tools\ps\wf> Invoke-Command -Session $s {Get-Job 2}

Id Name PSJobTypeName State HasMoreData Location-- ---- ---