powershell - rip tutorial · 2019-01-18 · dsc 177 dsc 178 62: 179 179 179 examples 179 179 179...

240
PowerShell #powershell

Upload: others

Post on 19-Jul-2020

37 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PowerShell

#powershell

Page 2: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

1

1: PowerShell 2

2

2

Examples 2

2

Windows 3

3

3

4

- PowerShell 5

6

.NET 6

7

2: ActiveDirectory 9

9

9

Examples 9

9

9

9

10

10

3: Amazon WebAWSSimple Storage ServiceS3 12

12

12

Examples 12

S3 12

S3 12

S3 13

4: Amazon WebAWS 14

Page 3: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

14

Examples 14

AWS 14

AWS 14

5: CSV 16

Examples 16

Import-Csv 16

CSV 16

6: DSC 18

18

18

Examples 18

DSC 18

KeyDSC 18

DSC 19

DSC 19

7: ISE 21

21

Examples 21

21

8: MongoDB 22

22

Examples 22

PowerShellC1.7MongoDB 22

Powershell3 22

9: Pester 24

24

Examples 24

Pester 24

10: PowerShell.exe 26

26

Page 4: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Examples 27

27

-Command <> 27

-Command {scriptblock} 27

- - 27

28

28

28

11: PowerShell 29

29

Examples 29

29

29

31

31

31

32

12: Powershellv2.0Artifactory 33

33

Examples 33

artifcatPowershell 33

13: PowershellIPv4v6 34

34

Examples 34

IP 34

14: PowerShellTCP 36

Examples 36

TCP 36

TCP Sender 36

15: PowerShell "" 38

38

Page 5: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Examples 38

38

38

16: PowershellGUI 40

Examples 40

Get-ServiceWPF GUI 40

17: PowerShellSQL 42

42

42

42

Examples 44

SQLExample 44

SQLQuery 44

18: PowerShell 46

46

46

Examples 46

46

47

19: PowerShell 49

Examples 49

49

20: PowerShell 51

51

Examples 51

51

51

51

CmdLet 52

53

53

arry 53

Page 6: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

53

21: PowerShell 55

55

55

Examples 55

55

55

56

56

57

22: PowerShell 59

59

59

59

Examples 59

59

60

60

23: Powershell 62

62

Examples 63

63

24: Powershell 64

64

Examples 64

64

64

65

PowerShell 65

66

66

25: Powershell 67

Page 7: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

67

Examples 67

PowerShell Remoting 67

67

67

PowerShell 68

68

69

69

PSSessions 70

26: PowerShell 72

72

72

Examples 72

72

72

73

73

27: PowerShell 74

74

Examples 74

74

74

75

75

77

ValidateSet 77

ValidateRange 78

ValidatePattern 78

ValidateLength 78

ValidateCount 78

Page 8: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

ValidateScript 78

28: Psake 80

80

80

Examples 80

80

FormatTaskName 80

81

ContinueOnError 81

29: PSScriptAnalyzer - PowerShell 82

82

82

Examples 82

82

83

83

30: RESTful API 84

84

Examples 84

Slack.comWebhook 84

hipChat 84

PowerShellREST 84

PowerShellRESTPOST 85

PowerShellREST 85

31: SharePoint 86

Examples 86

SharePoint 86

86

86

32: ShouldProcess 88

88

88

Page 9: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

88

Examples 88

-WhatIf-Confirm 88

1ShouldProcess 88

88

33: URL/ 91

91

Examples 91

91

91

`[uri] :: EscapeDataString` 92

`[System.Web.HttpUtility] :: UrlEncode 93

`[uri] :: UnescapeDataStringURL 93

`[System.Web.HttpUtility] :: UrlDecodeURL 95

34: WMICIM 98

98

CIMWMI 98

98

Examples 99

99

CIM 99

99

WQL 100

101

101

101

102

103

35: XML 104

Examples 104

XML 104

Page 10: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

XmlWriterXML 106

XMLDocumentXML 107

107

XML 107

108

109

109

111

111

36: 112

112

112

112

112

Examples 113

113

ZIPCompress-Archive 113

Expand-Archive 113

37: 114

114

Examples 114

114

38: 115

115

Examples 116

Get-Alias 116

116

39: 118

118

Examples 118

118

Page 11: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

40: 120

Examples 120

120

120

120

121

1 121

2Select-Object 121

3pscustomobjectPSv3 + 122

122

123

41: 125

125

Examples 125

125

125

42: 126

126

Examples 126

126

128

43: 131

131

131

Examples 131

131

Regexswitch 131

132

switch 132

switch 132

CaseSensitiveSwitch 133

Page 12: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

switch 133

134

134

44: 135

135

135

Examples 135

PowerShell 135

admininstrator 135

45: 136

136

Examples 136

PowerShell 136

46: 137

137

137

Examples 137

137

Splatting 137

138

138

47: 140

Examples 140

140

140

140

48: 141

Examples 141

.Net 141

49: 142

142

Examples 142

Page 13: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PowerShell 142

PowerShell 142

142

142

142

142

50: 144

144

144

Examples 144

144

144

145

145

145

146

51: 147

147

Examples 147

147

147

148

52: 149

149

Examples 149

$ PSScriptRoot 149

$ Args 149

$ PSItem 149

$ 150

$ 150

53: 151

151

Page 14: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Examples 151

151

Get-Help 151

152

152

152

152

54: C| VB 153

153

153

153

153

CSharp.NET 153

Examples 153

C 153

VB.NET 154

55: 156

156

Examples 156

156

156

156

157

157

158

158

56: 161

161

161

161

161

161

Page 15: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Examples 162

162

162

163

ForEach-Object 163

163

164

164

ForEach 165

165

166

57: 167

167

Examples 167

ErrorAction 167

-ErrorAction 167

-ErrorAction 167

-ErrorAction Inquire 168

-ErrorAction 168

-ErrorAction Stop 168

-ErrorAction Suspend 168

58: 170

Examples 170

170

59: 171

171

171

Examples 171

Where-Object / where / 171

/ 172

- / 173

Page 16: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Select-Object / select 173

60: 175

Examples 175

175

GUI 175

175

175

61: 177

Examples 177

- WindowsFeature 177

DSCmof 177

psd1 177

DSC 177

DSC 178

62: 179

179

179

Examples 179

179

179

179

179

180

Here-string 180

Here-string 180

here-string 180

181

181

+ 181

181

181

Page 17: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

63: 183

183

Examples 183

GUID 183

.NET 183

184

64: 185

185

185

Examples 185

ifelseelse if 185

185

186

65: 187

187

Examples 187

187

-Match 187

188

[RegEx] :: Match 189

189

-Replace 189

[RegEx] :: Replace 190

MatchEvalutor 190

191

191

191

[RegEx] :: Matches 192

66: 194

194

Examples 194

Page 18: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

194

194

194

194

195

196

196

67: 198

Examples 198

WindowsEnvPS 198

$ env 198

68: 199

199

Examples 199

199

199

199

Encrypter 200

200

200

69: 202

202

202

Examples 202

202

Set-ExecutionPolicy 203

203

203

204

205

205

70: 206

Page 19: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

206

206

Examples 206

$ pid 206

206

$ null 206

$ OFS 207

$ _ / $ PSItem 207

$ 207

$ 208

71: - 2 209

209

209

Examples 209

$ PSVersionTable 209

72: 210

210

Examples 210

KB - 210

73: 211

211

Examples 211

211

212

74: 214

214

214

Examples 215

Send-MailMessage 215

Send-MailMessage 215

SMTPClient - .txt 215

217

Page 20: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: powershell

It is an unofficial and free PowerShell ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official PowerShell.

The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.

Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected]

https://riptutorial.com/ja/home 1

Page 21: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

1: PowerShellをいめるWindows PowerShellは、.NET FrameworkにされたMicrosoftの/フレームワークであるWindows

Management Frameworkのシェルおよびスクリプトコンポーネントです。 PowerShellは、Windows 7 / Windows Server 2008 R2、サポートされているWindowsクライアントおよびサーバーオペレーティングシステムのすべてのバージョンにでインストールされます。 Powershellは、 Windowsフレームワーク WMFのそれのバージョンをダウンロードすることにより、いつでもすることができます。 PowerShell 6の「Alpha」バージョンはクロスプラットフォームWindows、Linux、およびOS Xであり、 このリリースページからダウンロードしてインストールするがあります 。

そののリソース

MSDNドキュメント https : //msdn.microsoft.com/en-us/powershell/scripting/powershell-scripting

TechNet https : //technet.microsoft.com/en-us/scriptcenter/dd742419.aspxページについて○

PowerShellギャラリー https : //www.powershellgallery.com/•

MSDNブログ https : //blogs.msdn.microsoft.com/powershell/•Github https : //github.com/powershell•コミュニティサイト http : //powershell.com/cs/•

バージョン

バージョン Windowsにまれる ノート

1.0 XP / Server 2008 2006-11-01

2.0 7 / Server 2008 R2 2009-11-01

3.0 8 / Server 2012 2012-08-01

4.0 8.1 / Server 2012 R2 2013-11-01

5.0 10 / Server 2016 Techプレビュー 2015-12-16

5.1 10/サーバー2016 2017-01-27

Examples

インストールまたはセットアップ

https://riptutorial.com/ja/home 2

Page 22: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Windows

PowerShellはWindows Management Frameworkにまれています。のWindowsでは、インストールとセットアップはです。

PowerShellのは、Windows Management Frameworkのしいバージョンをインストールすることでできます。

そののプラットフォーム

PowerShell 6の「ベータ」はのプラットフォームにもインストールできます。インストールパッケージはこちらからできます 。

たとえば、Ubuntu 16.04のPowerShell 6は、なインストールおよびのためにパッケージリポジトリにされています。

インストールするには、をします。

# Import the public repository GPG keys curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - # Register the Microsoft Ubuntu repository curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list # Update apt-get sudo apt-get update # Install PowerShell sudo apt-get install -y powershell # Start PowerShell powershell

Microsoftのリポジトリをスーパーユーザーとしてしたは、 sudo apt-get upgrade powershellをしてするだけでみます。それからpowershellするだけpowershell

マシンにされているスクリプトのなしをする

セキュリティのから、PowerShellはできスクリプトののみをするようにされています。のコマンドをすると、のないスクリプトをできますこれをうには、としてPowerShellをするがあります。

Set-ExecutionPolicy RemoteSigned

PowerShellスクリプトをするのは、 BypassをExecutionPolicyとしてすることです。

powershell.exe -ExecutionPolicy Bypass -File "c:\MyScript.ps1"

https://riptutorial.com/ja/home 3

Page 23: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

または、のコマンドをして、のPowerShellコンソールまたはISEセッションからいます。

Set-ExecutionPolicy Bypass Process

ポリシーのなは、 -ExecutionPolicyファイルをし、なポリシーを-ExecutionPolicyパラメーターとしてすことによってもできます。ポリシーはプロセスののみであるため、レジストリにするアクセスはありません。

C:\>powershell -ExecutionPolicy RemoteSigned

にものポリシーがされており、オンラインのサイトでは、しばしばSet-ExecutionPolicy

Unrestrictedをすることをおめします。このポリシーはされるまでそのままり、システムのセキュリティスタンスをさせます。これはおめできません。 RemoteSignedは、ローカルにされ、されたコードをし、リモートでしたコードにされたルートのでするがあるためされます。

また、ポリシーがグループポリシーによってされることにしてください。ポリシーがUnrestricted

システムにされても、グループポリシーはのは15でそのをにすがあります。 Get-ExecutionPolicy -Listをして、さまざまなスコープでポリシーセットをできます

TechNetドキュメント Set-ExecutionPolicy about_Execution_Policies

エイリアスとの

PowerShellでは、じをするためのくのがあります。これはシンプルでおなじみのHello Worldでうまくできます

Write-Host

Write-Host "Hello World"

Write-Output

Write-Output 'Hello world'

Write-Output Write-Hostがにきむにもかかわらず、ないがあることはにする。 Write-Hostはstdout

コンソールにのみきみますが、 Write-Outputはstdout と[success]ストリームのにきみをい、 リダイレクトをします。リダイレクトおよびなストリームでは、1つのコマンドのをへのをむのコマンドへのとしてすることができます。

> $message = Write-Output "Hello World" > $message "Hello World"

これらのはエイリアスではありませんが、ストリームを「」させたくないはじがられます。

https://riptutorial.com/ja/home 4

Page 24: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Write-OutputはEchoまたはWriteエイリアスされます

Echo 'Hello world' Write 'Hello world'

または、に「Hello world」とするだけです

'Hello world'

これらのすべてがされるコンソールになります

Hello world

PowerShellのエイリアスののとして、いコマンドプロンプトコマンドとBASHコマンドをPowerShellコマンドレットににマッピングするがあります。のすべては、のディレクトリのディレクトリリストをします。

C:\Windows> dir C:\Windows> ls C:\Windows> Get-ChildItem

に、Set-Aliasコマンドレットをしてのエイリアスをできます。として、 Test-NetConnection にはコマンドプロンプトのpingコマンドとのPowerShellを「ping」とします。

Set-Alias -Name ping -Value Test-NetConnection

Test-NetConnectionわりにpingをできるようになりましたエイリアスがすでにされているは、けをきすることにしてください。

エイリアスは、セッションがアクティブになるまでです。セッションをじて、のセッションでしたエイリアスをしようとすると、しません。このをするには、をするに、エキスパートのすべてのエイリアスをセッションにインポートします。

パイプライン - PowerShellコマンドレットからのの

PowerShellをしてスクリプトをするときににしたことの1つは、コマンドレットのをしてのをするです。

パイプライン|コマンドレットのでされ、エクスポートされたデータをのコマンドレットにフィードします。なは、Get-ChildItemからされるファイルのNameプロパティのみをするためにSelect-

Objectをすることです。

Get-ChildItem | Select-Object Name #This may be shortened to: gci | Select Name

https://riptutorial.com/ja/home 5

Page 25: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

よりなパイプラインのにより、コマンドレットのをforeachループにパイプすることができます。

Get-ChildItem | ForEach-Object { Copy-Item -Path $_.FullName -destination C:\NewDirectory\ } #This may be shortened to: gci | % { Copy $_.FullName C:\NewDirectory\ }

のでは、$ _をしています。 $ _は$ PSItemのいエイリアスで、パイプラインののをむです。

コメント

# ハッシュをしてをすることによってパワースクリプトにコメントする

# This is a comment in powershell Get-ChildItem

また、コメントのとにそれぞれ<#と#>をしてのコメントをけることもできます。

<# This is a multi-line comment #> Get-ChildItem

.NETライブラリメソッドのびし

Static .NetライブラリメソッドはPowerShellからびすことができます。これは、なクラスを3のにカプセルし、に::

#calling Path.GetFileName() C:\> [System.IO.Path]::GetFileName('C:\Windows\explorer.exe') explorer.exe

メソッドはクラスからびすことができますが、メソッドをびすには.Netクラスオブジェクトのインスタンスがです。

たとえば、AddHoursメソッドをSystem.DateTimeクラスからびすことはできません。クラスのインスタンスがです。

C:\> [System.DateTime]::AddHours(15) Method invocation failed because [System.DateTime] does not contain a method named 'AddHours'. At line:1 char:1 + [System.DateTime]::AddHours(15) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

https://riptutorial.com/ja/home 6

Page 26: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

この、にオブジェクトをします 。たとえば、のようにします 。

C:\> $Object = [System.DateTime]::Now

に、そのオブジェクトのメソッドをできます.AddHoursメソッドのように、System.DateTimeクラスからびすことのできないメソッドさえもできます。

C:\> $Object.AddHours(15) Monday 12 September 2016 01:51:19

オブジェクトの

New-Objectコマンドレットは、オブジェクトのにされます。

# Create a DateTime object and stores the object in variable "$var" $var = New-Object System.DateTime # calling constructor with parameters $sr = New-Object System.IO.StreamReader -ArgumentList "file path"

くの、しいオブジェクトがされ、データをエクスポートしたり、のコマンドレットにしたりします。これはそうすることができます

$newObject = New-Object -TypeName PSObject -Property @{ ComputerName = "SERVER1" Role = "Interface" Environment = "Production" }

オブジェクトをするはたくさんあります。 PSCustomObjectをするには、おそらくのがかつのPSCustomObject 。

$newObject = [PSCustomObject]@{ ComputerName = 'SERVER1' Role = 'Interface' Environment = 'Production' }

にオブジェクトをっていて、プロパティが1つまたは2つだけなは、 Select-Objectをしてそのプロパティをするだけです。

Get-ChildItem | Select-Object FullName, Name, @{Name='DateTime'; Expression={Get-Date}}, @{Name='PropertieName'; Expression={'CustomValue'}}

すべてのオブジェクトをにするか、パイプラインにすことができます。これらのオブジェクトをコレクションにし、にをすることもできます。

https://riptutorial.com/ja/home 7

Page 27: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

オブジェクトのコレクションはExport-CSVおよびImport-CSVでうまくします。 CSVのはオブジェクトであり、はプロパティです。

コマンドは、のためにオブジェクトをテキストストリームにします。オブジェクトのユーザビリティをするために、データのまでFormat- *コマンドをしないでください。

オンラインでPowerShellをいめるをむ https://riptutorial.com/ja/powershell/topic/822/powershellをいめる

https://riptutorial.com/ja/home 8

Page 28: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

2: ActiveDirectoryモジュール

このトピックでは、ユーザー、グループ、コンピューターおよびオブジェクトをするために、Active DirectoryモジュールでPowerShellにされるなコマンドレットをします。

PowerShellのヘルプシステムは、なのリソースの1つであることをえておいてください。

Get-Help Get-ADUser -Full Get-Help Get-ADGroup -Full Get-Help Get-ADComputer -Full Get-Help Get-ADObject -Full

すべてのヘルプドキュメントは、、、およびパラメータのヘルプをします。

Examples

モジュール

#Add the ActiveDirectory Module to current PowerShell Session Import-Module ActiveDirectory

ユーザー

Active Directoryユーザーをする

Get-ADUser -Identity JohnSmith

ユーザーにけられたすべてのプロパティをする

Get-ADUser -Identity JohnSmith -Properties *

ユーザーのしたプロパティをする

Get-ADUser -Identity JohnSmith -Properties * | Select-Object -Property sAMAccountName, Name, Mail

しいユーザー

New-ADUser -Name "MarySmith" -GivenName "Mary" -Surname "Smith" -DisplayName "MarySmith" -Path "CN=Users,DC=Domain,DC=Local"

グループ

https://riptutorial.com/ja/home 9

Page 29: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Active Directoryグループをする

Get-ADGroup -Identity "My-First-Group" #Ensure if group name has space quotes are used

グループにけられたすべてのプロパティをする

Get-ADGroup -Identity "My-First-Group" -Properties *

グループのすべてのメンバーをする

Get-ADGroupMember -Identity "My-First-Group" | Select-Object -Property sAMAccountName Get-ADgroup "MY-First-Group" -Properties Members | Select -ExpandProperty Members

ADユーザーをADグループにする

Add-ADGroupMember -Identity "My-First-Group" -Members "JohnSmith"

しいグループ

New-ADGroup -GroupScope Universal -Name "My-Second-Group"

コンピュータ

ADコンピュータをする

Get-ADComputer -Identity "JohnLaptop"

コンピュータにけられたすべてのプロパティをする

Get-ADComputer -Identity "JohnLaptop" -Properties *

コンピュータのプロパティのをする

Get-ADComputer -Identity "JohnLaptop" -Properties * | Select-Object -Property Name, Enabled

オブジェクト

Active Directoryオブジェクトの

#Identity can be ObjectGUID, Distinguished Name or many more Get-ADObject -Identity "ObjectGUID07898"

Active Directoryオブジェクトをする

Move-ADObject -Identity "CN=JohnSmith,OU=Users,DC=Domain,DC=Local" -TargetPath "OU=SuperUser,DC=Domain,DC=Local"

https://riptutorial.com/ja/home 10

Page 30: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Active Directoryオブジェクトをする

Set-ADObject -Identity "CN=My-First-Group,OU=Groups,DC=Domain,DC=local" -Description "This is My First Object Modification"

オンラインでActiveDirectoryモジュールをむ

https://riptutorial.com/ja/powershell/topic/8213/activedirectoryモジュール

https://riptutorial.com/ja/home 11

Page 31: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

3: Amazon WebサービスAWSSimple Storage ServiceS3

このドキュメントのセクションでは、Amazon Web ServicesAWSSimple Storage ServiceS3のにをてています。 S3はにやりとりするなサービスです。 0の "オブジェクト"をむS3バケットをします。バケットをしたら、ファイルまたはのデータをS3バケットに「オブジェクト」としてアップロードできます。オブジェクトの「キー」によって、バケットのS3オブジェクトをします。

パラメーター

パラメータ

BucketName あなたがしているAWS S3バケットの。

CannedACLName S3バケットにけられるみみのされたアクセスリストACLの。

ファイルAWS S3バケットにアップロードされるローカルファイルシステムのファイルの。

Examples

しいS3バケットをする

New-S3Bucket -BucketName trevor

シンプルストレージサービスS3バケットは、グローバルにでなければなりません。これは、するバケットをのかがすでにしているは、しいをするがあることをします。

S3バケットにローカルファイルをアップロードする

Set-Content -Path myfile.txt -Value 'PowerShell Rocks' Write-S3Object -BucketName powershell -File myfile.txt

ローカルファイルシステムからAWS S3へのファイルのアップロードは、 Write-S3Objectコマンドをするとです。そのもなでは、あなただけするが-BucketNameあなたにファイルをアップロードしたいS3バケットすために、パラメータを、および-Fileあなたがしたい、ローカルファイルへのパスまたはパスをすパラメータ、 S3バケットにアップロードします。

https://riptutorial.com/ja/home 12

Page 32: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

S3バケットの

Get-S3Object -BucketName powershell | Remove-S3Object -Force Remove-S3Bucket -BucketName powershell -Force

S3バケットをするには、そのバケットにされているすべてのS3オブジェクトをするがあります。のでは、バケットのすべてのオブジェクトのリストをしてからRemove-S3Objectコマンドにパイプしてしています。すべてのオブジェクトがされたら、 Remove-S3Bucketコマンドをしてバケットをできます。

オンラインでAmazon WebサービスAWSSimple Storage ServiceS3をむ

https://riptutorial.com/ja/powershell/topic/9579/amazon-webサービス-aws-simple-storage-service-s3-

https://riptutorial.com/ja/home 13

Page 33: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

4: Amazon WebサービスAWS

Amazon Rekognitionは、アプリケーションにをにできるサービスです。では、のオブジェクト、シーン、およびをできます。をしてすることもできます。 RekognitionのAPIをすると、なベースのビジュアルとをアプリケーションにくできます。

Examples

AWSによるラベルの

$BucketName = 'trevorrekognition' $FileName = 'kitchen.jpg' New-S3Bucket -BucketName $BucketName Write-S3Object -BucketName $BucketName -File $FileName $REKResult = Find-REKLabel -Region us-east-1 -ImageBucket $BucketName -ImageName $FileName $REKResult.Labels

のスクリプトをした、PowerShellホストにのようながされます。

RESULTS: Confidence Name ---------- ---- 86.87605 Indoors 86.87605 Interior Design 86.87605 Room 77.4853 Kitchen 77.25354 Housing 77.25354 Loft 66.77325 Appliance 66.77325 Oven

AWS RekognitionサービスとAWS PowerShellモジュールをすることで、ルームのオブジェクトの、したの、AWS Rekognitionがそれぞれのにしてっているレベルなど、イメージのラベルをできます。

Find-REKLabelコマンドは、これらの/ラベルのをびすことができるコマンドです。 APIびしにイメージコンテンツをバイトとしてすることができますが、よりいは、イメージファイルをAWS S3

バケットにアップロードしてから、するS3オブジェクトにRekognitionサービスをポイントすることです。のは、これをするをしています。

のとAWSの

https://riptutorial.com/ja/home 14

Page 34: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$BucketName = 'trevorrekognition' ### Create a new AWS S3 Bucket New-S3Bucket -BucketName $BucketName ### Upload two different photos of myself to AWS S3 Bucket Write-S3Object -BucketName $BucketName -File myphoto1.jpg Write-S3Object -BucketName $BucketName -File myphoto2.jpg ### Perform a facial comparison between the two photos with AWS Rekognition $Comparison = @{ SourceImageBucket = $BucketName TargetImageBucket = $BucketName SourceImageName = 'myphoto1.jpg' TargetImageName = 'myphoto2.jpg' Region = 'us-east-1' } $Result = Compare-REKFace @Comparison $Result.FaceMatches

のスクリプトのでは、のようながられます。

Face Similarity ---- ---------- Amazon.Rekognition.Model.ComparedFace 90

AWS Rekognitionサービスでは、2つのののをうことができます。このサービスのはにです。したい2つのファイルをAWS S3 Bucketにアップロードするだけです。に、のとのCompare-REKFaceコマンドをびします。もちろん、のにユニークなS3バケットとファイルをするがあります。

オンラインでAmazon WebサービスAWSをむ

https://riptutorial.com/ja/powershell/topic/9581/amazon-webサービス-aws-

https://riptutorial.com/ja/home 15

Page 35: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

5: CSV

Examples

Import-Csvのない

えられたのCSVファイル

String,DateTime,Integer First,2016-12-01T12:00:00,30 Second,2015-12-01T12:00:00,20 Third,2015-12-01T12:00:00,20

Import-CsvコマンドをしてPowerShellオブジェクトのCSVをインポートすることができます

> $listOfRows = Import-Csv .\example.csv > $listOfRows String DateTime Integer ------ -------- ------- First 2016-12-01T12:00:00 30 Second 2015-11-03T13:00:00 20 Third 2015-12-05T14:00:00 20 > Write-Host $row[0].String1 Third

CSVからインポートし、しいタイプにプロパティをキャストする

デフォルトでは、 Import-CSVはすべてのをとしてImport-CSVするため、DateTimeオブジェクトとオブジェクトをするには、それらをキャストまたはするがあります。

Foreach-Object

> $listOfRows = Import-Csv .\example.csv > $listOfRows | ForEach-Object { #Cast properties $_.DateTime = [datetime]$_.DateTime $_.Integer = [int]$_.Integer #Output object $_ }

されたプロパティの

> $listOfRows = Import-Csv .\example.csv > $listOfRows | Select-Object String, @{name="DateTime";expression={ [datetime]$_.DateTime }}, @{name="Integer";expression={ [int]$_.Integer }}

https://riptutorial.com/ja/home 16

Page 36: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

String DateTime Integer ------ -------- ------- First 01.12.2016 12:00:00 30 Second 03.11.2015 13:00:00 20 Third 05.12.2015 14:00:00 20

オンラインでCSVをむ https://riptutorial.com/ja/powershell/topic/5691/csv

https://riptutorial.com/ja/home 17

Page 37: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

6: DSCクラスベースのリソースの

PowerShellバージョン5.0では、PowerShellクラスをしてDesired State ConfigurationDSCリソースをできます。

DSCリソースのをするために、クラスにされる[DscResource()]と、DSCリソースユーザーがなプロパティをする[DscProperty()]リソースがあります。

クラスベースのDSCリソースは、のをたすがあります。

[DscResource()]でされている•[bool]をすTest()メソッドをします[bool]•のオブジェクトをすGet()メソッドをする [Ticket] •

[void]をすSet()メソッドをする•なくとも1つのKey DSCプロパティ•

クラスベースのPowerShell DSCリソースをしたは、モジュールマニフェスト.psd1ファイルをしてモジュールから「エクスポート」するがあります。モジュールマニフェストでは、 DscResourcesToExportハッシュテーブルキーをして、DSCリソースクラスのをモジュールから「エクスポート」することをします。これにより、DSCモジュールのは、モジュールのクラスベースのリソースを「る」ことができます。

Examples

DSCリソーススケルトンクラスをする

[DscResource()] class File { }

このでは、DSCリソースをするPowerShellクラスのセクションをするをします。クラスのをするがあります。

KeyプロパティをつDSCリソーススケルトン

[DscResource()] class Ticket { [DscProperty(Key)] [string] $TicketId }

DSCリソースは、なくとも1つのキープロパティをするがあります。なプロパティは、のリソー

https://riptutorial.com/ja/home 18

Page 38: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

スからリソースをにするためのものです。たとえば、チケットシステムでチケットをすDSCリソースをしているとします。チケットはチケットIDでにされます。

DSCリソースのユーザーにされるプロパティは、 [DscProperty()]で[DscProperty()]されていなければなりません。このは、プロパティがDSCリソースのキーであることをすために、 keyパラメータをけれます。

プロパティきDSCリソース

[DscResource()] class Ticket { [DscProperty(Key)] [string] $TicketId [DscProperty(Mandatory)] [string] $Subject }

DSCリソースをするには、すべてのプロパティがであるはないことがよくあります。ただし、DSCリソースのユーザーによってされることをにしたいいくつかのコアプロパティがあります。 [DscResource()]のMandatoryパラメータをして、DSCリソースのユーザーがとするプロパティをします。

のでは、 TicketリソースにSubjectプロパティをしましたSubjectリソースはチケットシステムののチケットをし、 Mandatoryプロパティとしてされています。

なメソッドをつDSCリソース

[DscResource()] class Ticket { [DscProperty(Key)] [string] $TicketId # The subject line of the ticket [DscProperty(Mandatory)] [string] $Subject # Get / Set if ticket should be open or closed [DscProperty(Mandatory)] [string] $TicketState [void] Set() { # Create or update the resource } [Ticket] Get() { # Return the resource's current state as an object $TicketState = [Ticket]::new() return $TicketState } [bool] Test() { # Return $true if desired state is met

https://riptutorial.com/ja/home 19

Page 39: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# Return $false if desired state is not met return $false } }

これは、なリソースをするためのすべてのコアをすなDSCリソースです。メソッドのはではありませんが、なをすがあります。

オンラインでDSCクラスベースのリソースのをむ

https://riptutorial.com/ja/powershell/topic/8733/dscクラスベースのリソースの

https://riptutorial.com/ja/home 20

Page 40: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

7: ISEモジュール

Windows PowerShell ISEIntegrated Scripting Environmentは、グラフィカルでなでスクリプトやモジュールの、、テストをにするホストアプリケーションです。 Windows PowerShell ISEのなには、シンタックスカラーリング、タブ、Intellisense、ビジュアルデバッグ、Unicode、ヘルプなどがあり、なスクリプティングエクスペリエンスをします。

Examples

テストスクリプト

ISEのシンプルでないは、コードをなカラーリングでいて、コードをマークしてF8キーをすだけです。

function Get-Sum { foreach ($i in $Input) {$Sum += $i} $Sum 1..10 | Get-Sum #output 55

オンラインでISEモジュールをむ https://riptutorial.com/ja/powershell/topic/10954/iseモジュール

https://riptutorial.com/ja/home 21

Page 41: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

8: MongoDB

もしいは、 サブをしていないにサブをすることです。 サブがなは、forループをにりし、 $doc2.add("Key", "Value")をするわりに、インデックスをつforeachのをします。これは、 "Tags" = [MongoDB.Bson.BsonDocument] $doc2ように、2でサブ"Tags" = [MongoDB.Bson.BsonDocument] $doc2ます。

Examples

PowerShellをしたCドライバ1.7のMongoDB

マシンからすべてのをし、MongoDBにするがあります。

Which require the output look like this. { "_id" : ObjectId("5800509f23888a12bccf2347"), "ResourceGrp" : "XYZZ-MachineGrp", "ProcessTime" : ISODate("2016-10-14T03:27:16.586Z"), "SubscriptionName" : "GSS", "OS" : "Windows", "HostName" : "VM1", "IPAddress" : "192.168.22.11", "Tags" : { "costCenter" : "803344", "BusinessUNIT" : "WinEng", "MachineRole" : "App", "OwnerEmail" : "[email protected]", "appSupporter" : "Steve", "environment" : "Prod", "implementationOwner" : "[email protected]", "appSoftware" : "WebServer", "Code" : "Gx", "WholeOwner" : "[email protected]" }, "SubscriptionID" : "", "Status" : "running fine", "ResourceGroupName" : "XYZZ-MachineGrp", "LocalTime" : "14-10-2016-11:27" }

はPowershellに3セットのをっています

$MachinesList # Array $ResourceList # Array $MachineTags # Array pseudo code $mongoDriverPath = 'C:\Program Files (x86)\MongoDB\CSharpDriver 1.7'; Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll"; Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";

https://riptutorial.com/ja/home 22

Page 42: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://127.0.0.1:2701/RGrpMachines'); [System.Collections.ArrayList]$TagList = $vm.tags $A1 = $Taglist.key $A2 = $Taglist.value foreach ($Machine in $MachinesList) { foreach($Resource in $ResourceList) { $doc2 = $null [MongoDB.Bson.BsonDocument] $doc2 = @{}; #Create a Document here for($i = 0; $i -lt $TagList.count; $i++) { $A1Key = $A1[$i].ToString() $A2Value = $A2[$i].toString() $doc2.add("$A1Key", "$A2Value") } [MongoDB.Bson.BsonDocument] $doc = @{ "_id"= [MongoDB.Bson.ObjectId]::GenerateNewId(); "ProcessTime"= [MongoDB.Bson.BsonDateTime] $ProcessTime; "LocalTime" = "$LocalTime"; "Tags" = [MongoDB.Bson.BsonDocument] $doc2; "ResourceGrp" = "$RGName"; "HostName"= "$VMName"; "Status"= "$VMStatus"; "IPAddress"= "$IPAddress"; "ResourceGroupName"= "$RGName"; "SubscriptionName"= "$CurSubName"; "SubscriptionID"= "$subid"; "OS"= "$OSType"; }; #doc loop close $collection.Insert($doc); } }

オンラインでMongoDBをむ https://riptutorial.com/ja/powershell/topic/7438/mongodb

https://riptutorial.com/ja/home 23

Page 43: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

9: PesterのPesterはPowerShellのテストフレームワークで、PowerShellコードのテストケースをできます。それはexをするためにすることができます。あなたのモジュール、スクリプトなどがしたとおりにすることをするのにつテスト。

Pesterとはですか、はにするがありますか

Examples

Pester

PesterモジュールをしてテストPowerShellコードをするには、3つのキーワード/コマンドにしているがあります。

テストのグループをします。すべてのPesterテストファイルにはなくとも1つのDescribe-

blockがです。•

それは々のテストをします。 DescripeブロックにのItブロックをくことができます。•

/ testコマンドをしますするがあります。これは、したテストとみなすべきをするためにされます。

サンプル

Import-Module Pester #Sample function to run tests against function Add-Numbers{ param($a, $b) return [int]$a + [int]$b } #Group of tests Describe "Validate Add-Numbers" { #Individual test cases It "Should add 2 + 2 to equal 4" { Add-Numbers 2 2 | Should Be 4 } It "Should handle strings" { Add-Numbers "2" "2" | Should Be 4 } It "Should return an integer"{ Add-Numbers 2.3 2 | Should BeOfType Int32 } }

Describing Validate Add-Numbers

https://riptutorial.com/ja/home 24

Page 44: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

[+] Should add 2 + 2 to equal 4 33ms [+] Should handle strings 19ms [+] Should return an integer 23ms

オンラインでPesterのをむ https://riptutorial.com/ja/powershell/topic/5753/pesterの

https://riptutorial.com/ja/home 25

Page 45: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

10: PowerShell.exeコマンドライン

パラメーター

パラメータ

- ヘルプ| - | / ヘルプをします

-File <FilePath> [<Args>]すべきスクリプトファイルへのパスとオプション

- コマンド{ - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>]}

のにされるコマンド

-EncodedCommand <Base64EncodedCommand>

Base64でエンコードされたコマンド

-ExecutionPolicy <ExecutionPolicy> このプロセスのポリシーのみをします。

-InputFormat {テキスト| XML}するデータのをします。テキストまたはXMLシリアルされたCLIXML

-MtaPowerShell 3.0マルチスレッドアパートメントでPowerShellをするSTAはデフォルト

-StaPowerShell 2.0シングルスレッドアパートメントでPowerShellをするMTAはデフォルト

-なしスクリプト/コマンドのにPowerShellコンソールをしたままにします。

-NoLogo にバナーをにする

- インタアクティブ ユーザーからコンソールをす

-NoProfileマシンまたはユーザーのPowerShellプロファイルのみみをける

-OutputFormat {Text | XML}PowerShellからされるデータのをします。テキストまたはXMLシリアルされたCLIXML

をする Export-Consoleをしてされたあらか-PSConsoleFile <FilePath>

https://riptutorial.com/ja/home 26

Page 46: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

パラメータ

じめされたコンソールファイルをみみます。

-Version <Windows PowerShellバージョン>するPowerShellのバージョンをします。ほとんど2.0されてい2.0

-WindowStyle <スタイル>PowerShellプロセスをnormal 、 hidden 、 minimizedまたはmaximizedウィンドウとしてするかをします。

Examples

コマンドの

-Commandパラメータは、にされるコマンドをするためにされます。のデータをサポートしています。

-Command <>

にするコマンドをですることができます。のセミコロン;されたがされることがあります。

>PowerShell.exe -Command "(Get-Date).ToShortDateString()" 10.09.2016 >PowerShell.exe -Command "(Get-Date).ToShortDateString(); 'PowerShell is fun!'" 10.09.2016 PowerShell is fun!

-Command {scriptblock}

-Commandパラメータは、スクリプトブロック{ #code }れた1つまたはのステートメントもサポートしています。これは、のWindows PowerShellセッションからPowerShell.exeをびすにのみします。

PS > powershell.exe -Command { "This can be useful, sometimes..." (Get-Date).ToShortDateString() } This can be useful, sometimes... 10.09.2016

- コマンド - https://riptutorial.com/ja/home 27

Page 47: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

-Command -をすると、からコマンドをすことができます。なは、 echo 、ファイルのみり、レガシーコンソールアプリケーションなどからるがあります。

>echo "Hello World";"Greetings from PowerShell" | PowerShell.exe -NoProfile -Command - Hello World Greetings from PowerShell

スクリプトファイルの

ファイルをps1して、に-Fileパラメータをしてコンテンツをすることが-Fileます。

なスクリプトMyScript.ps1

(Get-Date).ToShortDateString() "Hello World"

>PowerShell.exe -File Desktop\MyScript.ps1 10.09.2016 Hello World

パラメータとのファイルパスのにパラメータやをして、それらをスクリプトですることができます。は/なスクリプトパラメータのとしてされ、りは$args array

MyScript.ps1

param($Name) "Hello $Name! Today's date it $((Get-Date).ToShortDateString())" "First arg: $($args[0])"

>PowerShell.exe -File Desktop\MyScript.ps1 -Name StackOverflow foo Hello StackOverflow! Today's date it 10.09.2016 First arg: foo

オンラインでPowerShell.exeコマンドラインをむ

https://riptutorial.com/ja/powershell/topic/5839/powershell-exeコマンドライン

https://riptutorial.com/ja/home 28

Page 48: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

11: PowerShellクラス

クラスは、オブジェクトをするためのなプログラムコードテンプレートであり、メンバのとのメンバまたはメソッドをします。クラスはオブジェクトのです。これは、オブジェクトのをするモデルとしてされます。オブジェクトには、プロパティをしてアクセスし、メソッドをしてできるデータがまれています。 PowerShell 5.0にはのクラスをするがされました。

Examples

メソッドとプロパティ

class Person { [string] $FirstName [string] $LastName [string] Greeting() { return "Greetings, {0} {1}!" -f $this.FirstName, $this.LastName } } $x = [Person]::new() $x.FirstName = "Jane" $x.LastName = "Doe" $greeting = $x.Greeting() # "Greetings, Jane Doe!"

クラスのなコンストラクタをリストする

5.0

PowerShell 5.0では、new -methodをかっこなしでびすことにより、なコンストラクタをリストすることができます。

PS> [DateTime]::new OverloadDefinitions ------------------- datetime new(long ticks) datetime new(long ticks, System.DateTimeKind kind) datetime new(int year, int month, int day) datetime new(int year, int month, int day, System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second) datetime new(int year, int month, int day, int hour, int minute, int second, System.DateTimeKind kind) datetime new(int year, int month, int day, int hour, int minute, int second, System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond, System.DateTimeKind kind) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond,

https://riptutorial.com/ja/home 29

Page 49: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar, System.DateTimeKind kind)

これは、どのメソッドのオーバーロードをリストするのにもできるじテクニックです

> 'abc'.CompareTo OverloadDefinitions ------------------- int CompareTo(System.Object value) int CompareTo(string strB) int IComparable.CompareTo(System.Object obj) int IComparable[string].CompareTo(string other)

のバージョンでは、なコンストラクタをリストするのをできます。

function Get-Constructor { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [type]$type ) Process { $type.GetConstructors() | Format-Table -Wrap @{ n="$($type.Name) Constructors" e={ ($_.GetParameters() | % { $_.ToString() }) -Join ", " } } } }

Get-Constructor System.DateTime #Or [datetime] | Get-Constructor DateTime Constructors --------------------- Int64 ticks Int64 ticks, System.DateTimeKind kind Int32 year, Int32 month, Int32 day Int32 year, Int32 month, Int32 day, System.Globalization.Calendar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, System.DateTimeKind kind Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, System.Globalization.Calendar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, System.DateTimeKind kind Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, System.Globalization.Cal endar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, System.Globalization.Cal endar calendar, System.DateTimeKind kind

https://riptutorial.com/ja/home 30

Page 50: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

コンストラクタのオーバーロード

class Person { [string] $Name [int] $Age Person([string] $Name) { $this.Name = $Name } Person([string] $Name, [int]$Age) { $this.Name = $Name $this.Age = $Age } }

インスタンスのすべてのメンバーをする

PS > Get-Member -InputObject $anObjectInstance

これは、インスタンスのすべてのメンバーをします。は、Stringインスタンスのサンプルのです

TypeName: System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone(), System.Object ICloneable.Clone() CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB), i... Contains Method bool Contains(string value) CopyTo Method void CopyTo(int sourceIndex, char[] destination, int destinationI... EndsWith Method bool EndsWith(string value), bool EndsWith(string value, System.S... Equals Method bool Equals(System.Object obj), bool Equals(string value), bool E... GetEnumerator Method System.CharEnumerator GetEnumerator(), System.Collections.Generic... GetHashCode Method int GetHashCode() GetType Method type GetType() ...

クラステンプレート

# Define a class class TypeName { # Property with validate set [ValidateSet("val1", "Val2")] [string] $P1 # Static property static [hashtable] $P2 # Hidden property does not show as result of Get-Member

https://riptutorial.com/ja/home 31

Page 51: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

hidden [int] $P3 # Constructor TypeName ([string] $s) { $this.P1 = $s } # Static method static [void] MemberMethod1([hashtable] $h) { [TypeName]::P2 = $h } # Instance method [int] MemberMethod2([int] $i) { $this.P3 = $i return $this.P3 } }

クラスからクラスへの

class ParentClass { [string] $Message = "Its under the Parent Class" [string] GetMessage() { return ("Message: {0}" -f $this.Message) } } # Bar extends Foo and inherits its members class ChildClass : ParentClass { } $Inherit = [ChildClass]::new()

そう、 $ Inherit.Messageはあなたに

「そのクラスのに」

オンラインでPowerShellクラスをむ https://riptutorial.com/ja/powershell/topic/1146/powershellクラス

https://riptutorial.com/ja/home 32

Page 52: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

12: Powershellスクリプトv2.0をってArtifactoryからのアーティファクトをダウンロードするには

このドキュメントでは、Powershell Scriptv2.0またはそれをして、JFrog Artifactoryリポジトリからのアーティファクトをダウンロードするについてします。

Examples

のartifcatをダウンロードするPowershellスクリプト

$username = 'user' $password= 'password' $DESTINATION = "D:\test\latest.tar.gz" $client = New-Object System.Net.WebClient $client.Credentials = new-object System.Net.NetworkCredential($username, $password) $lastModifiedResponse = $client.DownloadString('https://domain.org.com/artifactory/api/storage/FOLDER/repo/?lastModified') [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer $getLatestModifiedResponse = $serializer.DeserializeObject($lastModifiedResponse) $downloaUriResponse = $getLatestModifiedResponse.uri Write-Host $json.uri $latestArtifcatUrlResponse=$client.DownloadString($downloaUriResponse) [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer $getLatestArtifact = $serializer.DeserializeObject($latestArtifcatUrlResponse) Write-Host $getLatestArtifact.downloadUri $SOURCE=$getLatestArtifact.downloadUri $client.DownloadFile($SOURCE,$DESTINATION)

オンラインでPowershellスクリプトv2.0をってArtifactoryからのアーティファクトをダウンロードするにはをむ https://riptutorial.com/ja/powershell/topic/8883/powershellスクリプト-v2-0-をってartifactoryからのアーティファクトをダウンロードするには-

https://riptutorial.com/ja/home 33

Page 53: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

13: PowershellでテキストファイルのIPv4とv6をする

IPv4とIPv6のをし、みまれたログファイルののIPアドレスできえます

Examples

テキストファイルのIPアドレスをする

# Read a text file and replace the IPv4 and IPv6 by fake IP Address # Describe all variables $SourceFile = "C:\sourcefile.txt" $IPv4File = "C:\IPV4.txt" $DestFile = "C:\ANONYM.txt" $Regex_v4 = "(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" $Anonym_v4 = "XXX.XXX.XXX.XXX" $Regex_v6 = "((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(([0-9A-Fa-f]{1,4}:){0,5}:((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|(::([0-9A-Fa-f]{1,4}:){0,5}((b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b).){3}(b((25[0-5])|(1d{2})|(2[0-4]d)|(d{1,2}))b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))" $Anonym_v6 = "YYYY:YYYY:YYYY:YYYY:YYYY:YYYY:YYYY:YYYY" $SuffixName = "-ANONYM." $AnonymFile = ($Parts[0] + $SuffixName + $Parts[1]) # Replace matching IPv4 from sourcefile and creating a temp file IPV4.txt Get-Content $SourceFile | Foreach-Object {$_ -replace $Regex_v4, $Anonym_v4} | Set-Content $IPv4File # Replace matching IPv6 from IPV4.txt and creating a temp file ANONYM.txt Get-Content $IPv4File | Foreach-Object {$_ -replace $Regex_v6, $Anonym_v6} | Set-Content $DestFile # Delete temp IPV4.txt file Remove-Item $IPv4File # Rename ANONYM.txt in sourcefile-ANONYM.txt $Parts = $SourceFile.Split(".") If (Test-Path $AnonymFile) { Remove-Item $AnonymFile Rename-Item $DestFile -NewName $AnonymFile }

https://riptutorial.com/ja/home 34

Page 54: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Else { Rename-Item $DestFile -NewName $AnonymFile }

オンラインでPowershellでテキストファイルのIPv4とv6をするをむ

https://riptutorial.com/ja/powershell/topic/9171/powershellでテキストファイルのip-v4とv6-をする

https://riptutorial.com/ja/home 35

Page 55: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

14: PowerShellとのTCP

Examples

TCPリスナー

Function Receive-TCPMessage { Param ( [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [int] $Port ) Process { Try { # Set up endpoint and start listening $endpoint = new-object System.Net.IPEndPoint([ipaddress]::any,$port) $listener = new-object System.Net.Sockets.TcpListener $EndPoint $listener.start() # Wait for an incoming connection $data = $listener.AcceptTcpClient() # Stream setup $stream = $data.GetStream() $bytes = New-Object System.Byte[] 1024 # Read data from stream and write it to host while (($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){ $EncodedText = New-Object System.Text.ASCIIEncoding $data = $EncodedText.GetString($bytes,0, $i) Write-Output $data } # Close TCP connection and stop listening $stream.close() $listener.stop() } Catch { "Receive Message failed with: `n" + $Error[0] } } }

のものをきめると、 $msgでメッセージをキャプチャします。

$msg = Receive-TCPMessage -Port 29800

TCP Sender

Function Send-TCPMessage { Param ( [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()]

https://riptutorial.com/ja/home 36

Page 56: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

[string] $EndPoint , [Parameter(Mandatory=$true, Position=1)] [int] $Port , [Parameter(Mandatory=$true, Position=2)] [string] $Message ) Process { # Setup connection $IP = [System.Net.Dns]::GetHostAddresses($EndPoint) $Address = [System.Net.IPAddress]::Parse($IP) $Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port) # Setup stream wrtier $Stream = $Socket.GetStream() $Writer = New-Object System.IO.StreamWriter($Stream) # Write message to stream $Message | % { $Writer.WriteLine($_) $Writer.Flush() } # Close connection and stream $Stream.Close() $Socket.Close() } }

メッセージをする

Send-TCPMessage -Port 29800 -Endpoint 192.168.0.1 -message "My first TCP message !"

TCPファイアウォールは、ソフトウェアファイアウォールや、しようとしているファイアウォールによってブロックされることがあります。のコマンドでしたTCPポートがいていて、じポートにリスナーがされていることをしてください。

オンラインでPowerShellとのTCPをむ https://riptutorial.com/ja/powershell/topic/5125/powershell

とのtcp

https://riptutorial.com/ja/home 37

Page 57: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

15: PowerShellの "ストリーム"。デバッグ、、、エラー、、およびhttps://technet.microsoft.com/en-us/library/hh849921.aspx

Examples

きみ

Write-Outputします。このは、パイプラインのののコマンドまたはコンソールにされるので、にされます。

コマンドレットは、オブジェクトをプライマリパイプライン「ストリーム」または「パイプライン」ともばれますにります。エラーオブジェクトをエラーパイプラインにするには、Write-Error

をします。

# 1.) Output to the next Cmdlet in the pipeline Write-Output 'My text' | Out-File -FilePath "$env:TEMP\Test.txt" Write-Output 'Bob' | ForEach-Object { "My name is $_" } # 2.) Output to the console since Write-Output is the last command in the pipeline Write-Output 'Hello world' # 3.) 'Write-Output' CmdLet missing, but the output is still considered to be 'Write-Output' 'Hello world'

Write-Outputコマンドレットは、されたオブジェクトをパイプラインをしてのコマンドにします。

1.

コマンドがパイプラインののコマンドである、オブジェクトはコンソールにされます。2. PowerShellインタプリタはこれをなWrite-Outputとしています。3.

Write-Outputのデフォルトのはパイプラインのにオブジェクトをするためですが、はCmdletをするはありません。たとえば、 Get-Process | Write-OutputはGet-Processとです。

をきむ

メッセージはのようにくことができます。

Write-Verbose "Detailed Message" Write-Information "Information Message" Write-Debug "Debug Message" Write-Progress "Progress Message" Write-Warning "Warning Message"

https://riptutorial.com/ja/home 38

Page 58: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

これらのそれぞれにはがあります。

$VerbosePreference = "SilentlyContinue" $InformationPreference = "SilentlyContinue" $DebugPreference = "SilentlyContinue" $ProgressPreference = "Continue" $WarningPreference = "Continue"

プリファレンスは、メッセージとそれにくスクリプトのをします。

$InformationPreference = "SilentlyContinue" Write-Information "This message will not be shown and execution continues" $InformationPreference = "Continue" Write-Information "This message is shown and execution continues" $InformationPreference = "Inquire" Write-Information "This message is shown and execution will optionally continue" $InformationPreference = "Stop" Write-Information "This message is shown and execution terminates"

メッセージのは、のようにすることでWrite-Errorできます。

$host.PrivateData.ErrorBackgroundColor = "Black" $host.PrivateData.ErrorForegroundColor = "Red"

Write-Verbose 、 Write-Debug 、 Write-Warningについてものがです。

オンラインでPowerShellの "ストリーム"。デバッグ、、、エラー、、およびをむ

https://riptutorial.com/ja/powershell/topic/3255/powershellの--ストリーム--デバッグ---エラー--および

https://riptutorial.com/ja/home 39

Page 59: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

16: PowershellのGUI

Examples

Get-ServiceコマンドレットのWPF GUI

Add-Type -AssemblyName PresentationFramework [xml]$XAMLWindow = ' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="Auto" SizeToContent="WidthAndHeight" Title="Get-Service"> <ScrollViewer Padding="10,10,10,0" ScrollViewer.VerticalScrollBarVisibility="Disabled"> <StackPanel> <StackPanel Orientation="Horizontal"> <Label Margin="10,10,0,10">ComputerName:</Label> <TextBox Name="Input" Margin="10" Width="250px"></TextBox> </StackPanel> <DockPanel> <Button Name="ButtonGetService" Content="Get-Service" Margin="10" Width="150px" IsEnabled="false"/> <Button Name="ButtonClose" Content="Close" HorizontalAlignment="Right" Margin="10" Width="50px"/> </DockPanel> </StackPanel> </ScrollViewer > </Window> ' # Create the Window Object $Reader=(New-Object System.Xml.XmlNodeReader $XAMLWindow) $Window=[Windows.Markup.XamlReader]::Load( $Reader ) # TextChanged Event Handler for Input $TextboxInput = $Window.FindName("Input") $TextboxInput.add_TextChanged.Invoke({ $ComputerName = $TextboxInput.Text $ButtonGetService.IsEnabled = $ComputerName -ne '' }) # Click Event Handler for ButtonClose $ButtonClose = $Window.FindName("ButtonClose") $ButtonClose.add_Click.Invoke({ $Window.Close(); }) # Click Event Handler for ButtonGetService $ButtonGetService = $Window.FindName("ButtonGetService") $ButtonGetService.add_Click.Invoke({ $ComputerName = $TextboxInput.text.Trim() try{ Get-Service -ComputerName $computerName | Out-GridView -Title "Get-Service on $ComputerName"

https://riptutorial.com/ja/home 40

Page 60: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

}catch{ [System.Windows.MessageBox]::Show($_.exception.message,"Error",[System.Windows.MessageBoxButton]::OK,[System.Windows.MessageBoxImage]::Error) } }) # Open the Window $Window.ShowDialog() | Out-Null

これにより、ユーザーがコンピュータをできるダイアログウィンドウがされ、そのコンピュータにサービスのテーブルとそのステータスがされます。 このでは、WindowsフォームではなくWPFをしています。

オンラインでPowershellのGUIをむ https://riptutorial.com/ja/powershell/topic/7141/powershellのgui

https://riptutorial.com/ja/home 41

Page 61: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

17: PowerShellのSQLクエリ

このドキュメントをむことで、PowerShellでSQLクエリをするをることができます

パラメーター

$ ServerInstanceここでは、データベースがするインスタンスについてするがあります

$データベース ここでは、テーブルがするデータベースについてするがあります

$クエリ ここでは、SQでしたいクエリがです

$ユーザーと$パスワード

データベースにアクセスできるユーザーとパスワード

SQLPSモジュールをインポートできないは、のをできます

function Import-Xls { [CmdletBinding(SupportsShouldProcess=$true)] Param( [parameter( mandatory=$true, position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [String[]] $Path, [parameter(mandatory=$false)] $Worksheet = 1, [parameter(mandatory=$false)] [switch] $Force ) Begin { function GetTempFileName($extension) { $temp = [io.path]::GetTempFileName(); $params = @{ Path = $temp;

https://riptutorial.com/ja/home 42

Page 62: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Destination = $temp + $extension; Confirm = $false; Verbose = $VerbosePreference; } Move-Item @params; $temp += $extension; return $temp; } # since an extension like .xls can have multiple formats, this # will need to be changed # $xlFileFormats = @{ # single worksheet formats '.csv' = 6; # 6, 22, 23, 24 '.dbf' = 11; # 7, 8, 11 '.dif' = 9; # '.prn' = 36; # '.slk' = 2; # 2, 10 '.wk1' = 31; # 5, 30, 31 '.wk3' = 32; # 15, 32 '.wk4' = 38; # '.wks' = 4; # '.xlw' = 35; # # multiple worksheet formats '.xls' = -4143; # -4143, 1, 16, 18, 29, 33, 39, 43 '.xlsb' = 50; # '.xlsm' = 52; # '.xlsx' = 51; # '.xml' = 46; # '.ods' = 60; # } $xl = New-Object -ComObject Excel.Application; $xl.DisplayAlerts = $false; $xl.Visible = $false; } Process { $Path | ForEach-Object { if ($Force -or $psCmdlet.ShouldProcess($_)) { $fileExist = Test-Path $_ if (-not $fileExist) { Write-Error "Error: $_ does not exist" -Category ResourceUnavailable; } else { # create temporary .csv file from excel file and import .csv # $_ = (Resolve-Path $_).toString(); $wb = $xl.Workbooks.Add($_); if ($?) { $csvTemp = GetTempFileName(".csv"); $ws = $wb.Worksheets.Item($Worksheet); $ws.SaveAs($csvTemp, $xlFileFormats[".csv"]); $wb.Close($false); Remove-Variable -Name ('ws', 'wb') -Confirm:$false;

https://riptutorial.com/ja/home 43

Page 63: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Import-Csv $csvTemp; Remove-Item $csvTemp -Confirm:$false -Verbose:$VerbosePreference; } } } } } End { $xl.Quit(); Remove-Variable -name xl -Confirm:$false; [gc]::Collect(); } }

Examples

SQLExample

MachineNameテーブルからすべてのデータをするには、のようなコマンドをできます。

$ Query = "Select * from MachineName"

$ Inst = "ServerInstance"

$ DbName = "DatabaseName

$ UID = "ユーザーID"

$ Password = "Password"

Invoke-Sqlcmd2 -Serverinstance $Inst -Database $DBName -query $Query -Username $UID -Password $Password

SQLQuery

MachineNameテーブルからすべてのデータをするには、のようなコマンドをできます。

$ Query = "Select * from MachineName"

$ Inst = "ServerInstance"

$ DbName = "DatabaseName

$ UID = "ユーザーID"

$ Password = "Password"

Invoke-Sqlcmd2 -Serverinstance $Inst -Database $DBName -query $Query -Username $UID -Password $Password

https://riptutorial.com/ja/home 44

Page 65: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

18: PowerShellのバックグラウンドジョブ

ジョブはPowerShell 2.0でされ、コマンドラインツールののにちました。にえば、しているタスクをすると、タスクがするまでプロンプトがされなくなります。されるタスクのとして、このなPowerShellコマンドをえてみましょう。

Get-ChildItem - パスc\ - レスキュー

Cドライブのなディレクトリリストをするのにがかかります。ジョブとしてすると、コンソールにコントロールがされ、でをできます。

PowerShellジョブはしいプロセスでされます。これにはするとがあります。

ジョブは、をむクリーンなプロセスでされます。1. ジョブは、PowerShellプロセスとでできます2.

プロセスのはジョブにはしません。1. パラメータはされ、されたはされます。

つまり、ジョブのにパラメータオブジェクトをすると、ジョブにされません。•これは、オブジェクトのシリアルができない、したりすことができないことをしますただし、PowerShellはパラメータをコピーしてPSObjectをすことがあります。

2.

Examples

なジョブの

バックグラウンドジョブとしてスクリプトブロックをする

$job = Start-Job -ScriptBlock {Get-Process}

バックグラウンドジョブとしてスクリプトをする

$job = Start-Job -FilePath "C:\YourFolder\Script.ps1"

リモートマシンでInvoke-Commandをしてジョブをする

$job = Invoke-Command -ComputerName "ComputerName" -ScriptBlock {Get-Service winrm} -JobName "WinRM" -ThrottleLimit 16 -AsJob

のユーザーとしてジョブをするパスワードをめるプロンプト

https://riptutorial.com/ja/home 46

Page 66: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Start-Job -ScriptBlock {Get-Process} -Credential "Domain\Username"

または

Start-Job -ScriptBlock {Get-Process} -Credential (Get-Credential)

ジョブをのユーザーとしてするプロンプトなし

$username = "Domain\Username" $password = "password" $secPassword = ConvertTo-SecureString -String $password -AsPlainText -Force $credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username, $secPassword) Start-Job -ScriptBlock {Get-Process} -Credential $credentials

なジョブ

のセッションのすべてのジョブのリストをします。

Get-Job

ジョブをってをるにする

$job | Wait-job | Receive-Job

がすぎるはジョブのタイムアウトこのでは10

$job | Wait-job -Timeout 10

ジョブをするするにそのジョブキューでのすべてのタスクをする。

$job | Stop-Job

のセッションのバックグラウンドジョブリストからジョブをする

$job | Remove-Job

は、 Workflowジョブでのみします。

Workflowジョブをする

$job | Suspend-Job

Workflowジョブをする

$job | Resume-Job

https://riptutorial.com/ja/home 47

Page 68: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

19: PowerShellのパラメータ

Examples

「シンプルな」パラメータ

このでは、 $SomeUsefulNumberが5よりきい、MyTestFunctionにしいパラメータをします。

function MyTestFunction { [CmdletBinding(DefaultParameterSetName='DefaultConfiguration')] Param ( [Parameter(Mandatory=$true)][int]$SomeUsefulNumber ) DynamicParam { $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "__AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) # If "SomeUsefulNumber" is greater than 5, then add the "MandatoryParam1" parameter if($SomeUsefulNumber -gt 5) { # Create a mandatory string parameter called "MandatoryParam1" $dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("MandatoryParam1", [String], $attributeCollection) # Add the new parameter to the dictionary $paramDictionary.Add("MandatoryParam1", $dynParam1) } return $paramDictionary } process { Write-Host "SomeUsefulNumber = $SomeUsefulNumber" # Notice that dynamic parameters need a specific syntax Write-Host ("MandatoryParam1 = {0}" -f $PSBoundParameters.MandatoryParam1) } }

PS > MyTestFunction -SomeUsefulNumber 3 SomeUsefulNumber = 3 MandatoryParam1 = PS > MyTestFunction -SomeUsefulNumber 6 cmdlet MyTestFunction at command pipeline position 1 Supply values for the following parameters:

https://riptutorial.com/ja/home 49

Page 69: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

MandatoryParam1: PS >MyTestFunction -SomeUsefulNumber 6 -MandatoryParam1 test SomeUsefulNumber = 6 MandatoryParam1 = test

2のでは、パラメータがしていることをにできます。

パラメータもでされます。 のにCtrl +スペースをすと、のようになります。

PS >MyTestFunction -SomeUsefulNumber 3 -<ctrl+space> Verbose WarningAction WarningVariable OutBuffer Debug InformationAction InformationVariable PipelineVariable ErrorAction ErrorVariable OutVariable PS >MyTestFunction -SomeUsefulNumber 6 -<ctrl+space> MandatoryParam1 ErrorAction ErrorVariable OutVariable Verbose WarningAction WarningVariable OutBuffer Debug InformationAction InformationVariable PipelineVariable

オンラインでPowerShellのパラメータをむ

https://riptutorial.com/ja/powershell/topic/6704/powershellのパラメータ

https://riptutorial.com/ja/home 50

Page 70: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

20: PowerShellの

はをするためにされます。をのにすると、コンソール/スクリプトでをできるように、をどこかにするがあります。 PowerShellのは$ Variable1のように$でまり、は$ Variable1 = "Value 1"のように=をしてりてられます.PowerShellはなのをサポートしています。、の、、さらにはバージョンやIPアドレスなどのなのような、

Examples

powershellのすべてのは、ドル $ でまります。これのもなはのとおりです。

$foo = "bar"

このは、 fooというに "bar"をりてます。

メモリからをするには、 Remove-Itemコマンドレットをします。には$はまれません。

Remove-Item Variable:\foo

Variableは、ほとんどの* -itemコマンドレットがファイルシステムのようにするようにするプロバイダがあります。

をするもう1つのは、Remove-Variableコマンドレットとそのエイリアスrvをすることです

$var = "Some Variable" #Define variable 'var' containing the string 'Some Variable' $var #For test and show string 'Some Variable' on the console Remove-Variable -Name var $var #also can use alias 'rv' rv var

のデフォルトスコープはみコンテナです。スクリプトのまたはのコンテナの、スコープはGlobal

です。 スコープをするには、$scope:varnameをけ$scope:varname like so

$foo = "Global Scope" function myFunc { $foo = "Function (local) scope" Write-Host $global:foo Write-Host $local:foo Write-Host $foo

https://riptutorial.com/ja/home 51

Page 71: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

} myFunc Write-Host $local:foo Write-Host $foo

Global Scope Function (local) scope Function (local) scope Global Scope Global Scope

CmdLetのみみ

デフォルトでは、powershellはをびしエンティティにします。のをして、

Get-Process -Name excel

これはに、がするのプロセスをびしのエンティティにします。この、PowerShellホスト。それは、

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id SI ProcessName ------- ------ ----- ----- ----- ------ -- -- ----------- 1037 54 67632 62544 617 5.23 4544 1 EXCEL

にをすると、もされません。もちろんはをします。 それはにしてください、オブジェクト - そのタイプののタイプ

$allExcel = Get-Process -Name excel

したがって、でをりてるシナリオがあるとします-OutVariableパラメータをできます

Get-Process -Name excel -OutVariable AllRunningExcel

「$」はここではつからないことにしてください。これらの2つのりてのないは、をAllRunningExcelにりてることかられてすることです。それをのにりてることもできます。

$VarOne = Get-Process -Name excel -OutVariable VarTwo

のシナリオはにまれですが、$ VarOneと$ VarTwoはじをちます。

これをえてみましょう。

Get-Process -Name EXCEL -OutVariable MSOFFICE Get-Process -Name WINWORD -OutVariable +MSOFFICE

のステートメントはにExcelプロセスをしてMSOFFICEにりて、にMSワードプロセスをし、

https://riptutorial.com/ja/home 52

Page 72: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

MSOFFICEののに「」します。それはこのようなものにえますが、

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id SI ProcessName ------- ------ ----- ----- ----- ------ -- -- ----------- 1047 54 67720 64448 618 5.70 4544 1 EXCEL 1172 70 50052 81780 584 1.83 14968 1 WINWORD

のリスト

Powershellは、ののりてをにし、やリストのようなほとんどすべてをいます。これは、のようなことをするのではなく、

$input = "foo.bar.baz" $parts = $input.Split(".") $foo = $parts[0] $bar = $parts[1] $baz = $parts[2]

これをにうことができます

$foo, $bar, $baz = $input.Split(".")

Powershellはリストのようにをしますので、リストにをりてるリストよりもくのがある、のはりののになります。つまり、のようなこともできる

$foo, $leftover = $input.Split(".") #Sets $foo = "foo", $leftover = ["bar","baz"] $bar = $leftover[0] # $bar = "bar" $baz = $leftover[1] # $baz = "baz"

Powershellのは、ののインスタンスとほとんどじです。つまり、 $name =をします。のは、カンマ

, でってします。

$myArrayOfInts = 1,2,3,4 $myArrayOfStrings = "1","2","3","4"

arryにする

にするには、 +をするのとじくらいです

$myArrayOfInts = $myArrayOfInts + 5 //now contains 1,2,3,4 & 5!

をまとめてみわせる

https://riptutorial.com/ja/home 53

Page 73: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

これも+をするのとじくらいです

$myArrayOfInts = 1,2,3,4 $myOtherArrayOfInts = 5,6,7 $myArrayOfInts = $myArrayOfInts + $myOtherArrayOfInts //now 1,2,3,4,5,6,7

オンラインでPowerShellのをむ https://riptutorial.com/ja/powershell/topic/3457/powershellの

https://riptutorial.com/ja/home 54

Page 74: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

21: PowerShellのり

のスコープをするためにすることができます。スコープは、、スクリプト、スクリプトブロックのいずれかです。 PowerShellでは、なReturnキーワードがなくても、またはスコープのわりにしたことをすために、ステートメントのがとしてされます。

りセマンティクスについてしくは、TechNetのabout_Returnページ、またはPowerShellプロンプトからget-help returnをびすことでごいただけます。

よりくの・があるなQAの

PowerShellのり•

PowerShellがなりをたない•

MSDNのabout_returnはそれをにしています

Returnキーワードは、、スクリプト、またはスクリプトブロックをします。のポイントでスコープをしたり、をしたり、スコープのわりにしたことをすためにできます。

CやCのようなにしているユーザーは、スコープをにすロジックをるために、Returnキーワードをすることができます。

Windows PowerShellでは、Returnキーワードをむステートメントがなくても、ステートメントのがとしてされます。 CやCのようなは、Returnキーワードでされたのみをします。

Examples

function earlyexit { "Hello" return "World" }

"Hello"はパイプラインにされ、 "World"はパイプラインにされません

ゴッチャパイプラインでのり

get-childitem | foreach-object { if ($_.IsReadOnly) { return } }

Pipelineコマンドレット ForEach-Object 、 Where-Objectなどはクロージャでします。ここでのりは

https://riptutorial.com/ja/home 55

Page 75: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

、パイプラインののにするだけで、にはされません。をするは、 returnのわりにbreakをできます。

get-childitem | foreach-object { if ($_.IsReadOnly) { break } }

ゴッチャなをする

インスピレーションをけた

PowerShellがなりをたない•

function bar { [System.Collections.ArrayList]$MyVariable = @() $MyVariable.Add("a") | Out-Null $MyVariable.Add("b") | Out-Null $MyVariable }

.NET ArrayList.Addメソッドはにコレクションのをすため、 Out-NullがArrayList.Add 。された、パイプラインは1, 2, "a", "b"

なをするには、のがあります。

function bar { # New-Item cmdlet returns information about newly created file/folder New-Item "test1.txt" | out-null New-Item "test2.txt" > $null [void](New-Item "test3.txt") $tmp = New-Item "test4.txt" }

なぜ> $nullをきなのかについては、[まだされていないトピック]をしてください。

をす

about_returnからのいえ

のメソッドは、パイプラインでじをちます

function foo { $a = "Hello" return $a } function bar { $a = "Hello" $a return } function quux {

https://riptutorial.com/ja/home 56

Page 76: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$a = "Hello" $a }

のい

は、かのものによってされていないものすべてをします。 returnキーワードをすると、りののすべてのはされません

このような

Function Test-Function { Param ( [switch]$ExceptionalReturn ) "Start" if($ExceptionalReturn){Return "Damn, it didn't work!"} New-ItemProperty -Path "HKCU:\" -Name "test" -Value "TestValue" -Type "String" Return "Yes, it worked!" }

テスト

ります

•しくされたレジストリキーこれは、していないをするがいくつかあるためです•はい、それはいた•

テスト-ExceptionalReturnり

•くそー、うまくいきませんでした•

あなたがこれをきなら、

Function Test-Function { Param ( [switch]$ExceptionalReturn ) . { "Start" if($ExceptionalReturn) { $Return = "Damn, it didn't work!" Return } New-ItemProperty -Path "HKCU:\" -Name "test" -Value "TestValue" -Type "String" $Return = "Yes, it worked!" Return } | Out-Null

https://riptutorial.com/ja/home 57

Page 77: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Return $Return }

テスト

ります

はい、それはいた•

テスト-ExceptionalReturnり

くそー、うまくいきませんでした•

このトリックでは、ステートメントがをきすのかからなくても、されるをできます。

それはこのようにします

.{<Statements>} | Out-Null

。のスクリプトブロックをコードにみみます

{}はスクリプトブロックをマークします

| Out-NullパイプはOut-Nullへのしないをパイプしますえました。 scriptblockがまれているので、りのとじスコープをします。 したがって、スクリプトブロックでされたにアクセスできます。

オンラインでPowerShellのりをむ https://riptutorial.com/ja/powershell/topic/4781/powershellのり

https://riptutorial.com/ja/home 58

Page 78: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

22: PowerShellパイプラインの

PowerShellにはオブジェクトパイプライニングモデルがされています。このモデルをすると、オブジェクトをパイプラインでしてコマンドレットやなくともすることができます。なベースのパイプライニングとはに、パイプオブジェクトのはのにあるはありません。コマンドレットは、パイプラインからのオブジェクトとすることをとしてし、りはパイプラインににされます。

BEGINのブロック。に1されます。ここでされるパイプラインは、されていないため、$ null

です。•

PROCESS 2のブロック。パイプラインのにしてされます。パイプラインパラメータは、されているとじです。

ENDのブロック。にだけされます。パイプラインパラメータは、されてからされていないため、ののとじです。

ほとんどの、パイプラインのはオブジェクトのになります。 PROCESS{}ブロックのはforeach{}ブロックのようにえるかもしれませんが、のをスキップするにはのプロセスがです。

foreach{}ように、 PROCESS{}ブロックでcontinueをすると、 END{}ブロックをむのすべてのステートメントをスキップしてパイプラインがされます。わりに、 returnします。ののPROCESS{}ブロックをし、のにします。

によっては、なるののをするがあります。 CmdLetsののは、 $OutputEncodingによってされます。をネイティブアプリケーションへのパイプラインにれることをしている、ターゲットとするようにエンコーディングをすることがましいでしょう。 $OutputEncoding = [Console]::OutputEncoding

そのの

$OutputEncodingにするよりしいをむブログhttps://blogs.msdn.microsoft.com/powershell/2006/12/11/outputencoding-to-the-rescue/

Examples

なライフサイクルをつの

このは、がパイプラインをけれ、にするをしています。

のbeginおよびendはパイプラインにはオプションですが、 ValueFromPipelineまたはValueFromPipelineByPropertyNameをするはそのprocessがです。

function Write-FromPipeline{ [CmdletBinding()] param(

https://riptutorial.com/ja/home 59

Page 79: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

[Parameter(ValueFromPipeline)] $myInput ) begin { Write-Verbose -Message "Beginning Write-FromPipeline" } process { Write-Output -InputObject $myInput } end { Write-Verbose -Message "Ending Write-FromPipeline" } } $foo = 'hello','world',1,2,3 $foo | Write-FromPipeline -Verbose

VERBOSE: Beginning Write-FromPipeline hello world 1 2 3 VERBOSE: Ending Write-FromPipeline

のパイプラインのサポート

これは、パイプラインのためのサポートがもなのです。 にすように、パイプラインをサポートしているには、ParameterAttribute ValueFromPipelineまたはValueFromPipelineByPropertyNameされたなくとも1つのパラメータがです。

function Write-FromPipeline { param( [Parameter(ValueFromPipeline)] # This sets the ParameterAttribute [String]$Input ) Write-Host $Input } $foo = 'Hello World!' $foo | Write-FromPipeline

Hello World!

PowerShell 3.0では、ParameterAttributesのデフォルトがサポートされています。のバージョンでは、 ValueFromPipeline=$trueするがあります。

パイプラインの

パイプラインシリーズでは、はスレッドのようにのとにされます。にされたオブジェクトはのパイプラインにされ、のはのスレッドでちにされます。これは、のForEachとしてゲインをしています

https://riptutorial.com/ja/home 60

Page 80: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

@( bigFile_1, bigFile_2, ..., bigFile_n) | Copy-File | Encrypt-File | Get-Md5

step - のファイルをコピーする Copy-file Thread1.

ステップ - 2ファイルをCopy-fileスレッドにCopy-file 、に1 Encrypt-FileをEncrypt-File2.

ステップ- のファイルをコピーするCopy-fileスレッドとにのファイルするEncrypt-File とにget-Md5 ののGet-Md5

3.

オンラインでPowerShellパイプラインのをむ

https://riptutorial.com/ja/powershell/topic/3937/powershellパイプラインの

https://riptutorial.com/ja/home 61

Page 81: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

23: Powershellプロファイルプロファイルファイルは、PowerShellコンソールのにされるpowershellスクリプトです。このようにして、しいPowerShellセッションをするたびにをすることができます。

powershell startでやりたいことのなものはのとおりです

にするモジュールのインポートActiveDirectory、Exchange、のDLL•

ロギング•プロンプトをする•

さまざまなとスタートアップのをつプロファイルファイルとがいくつかあります。

ホスト

ユーザー

パスをする

すべて

すべて

WINDIR\ System32 \ WindowsPowerShell \ v1.0 \ profile.ps1

1 $ profile.AllUsersAllHosts

すべて

USERPROFILE\ Documents \ WindowsPowerShell \ profile.ps1

3 $ profile.CurrentUserAllHosts

コンソール

すべて

WINDIR\ System32 \ WindowsPowerShell \ v1.0 \ Microsoft.PowerShell_profile.ps1

2 $ profile.AllUsersCurrentHost

コンソール

USERPROFILE\ Documents \ WindowsPowerShell \ Microsoft.PowerShell_profile.ps1

4$ profile.CurrentUserCurrentHost

ISEすべて

WINDIR\ System32 \ WindowsPowerShell \ v1.0 \ Microsoft.PowerShellISE_profile.ps1

2 $ profile.AllUsersCurrentHost

USERPROFILE\ Documents \ WindowsPowerShell \

ISE 4$ profile.CurrentUserCurrentHost

https://riptutorial.com/ja/home 62

Page 82: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

ホスト

ユーザー

パスをする

Microsoft.PowerShellISE_profile.ps1

Examples

プロファイルをする

PowerShellプロファイルは、ユーザーのとをにロードするためにされます。

PowerShellプロファイルはユーザーにしてにされません。

PowerShellプロファイルC:>New-Item -ItemType File $profileをするには

ISEにいるは、 C:>psEdit $profileというみみエディタをすることができC:>psEdit $profile

のホストのプロファイルをにめるには、 $profile -variableにされたパスにテキストをする

"#Current host, current user" > $profile

プロファイルをさらにするには、PowerShell ISE、メモ、Visual Studioコードまたはそののエディタをします。

$profile -variableはデフォルトでのホストののユーザープロファイルをしますが、machine-policy

すべてのユーザーへのパスおよび/またはすべてのホストコンソール、ISE、サードパーティのプロファイルにアクセスするには、それはプロパティです。

PS> $PROFILE | Format-List -Force AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1 CurrentUserAllHosts : C:\Users\user\Documents\WindowsPowerShell\profile.ps1 CurrentUserCurrentHost : C:\Users\user\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 Length : 75 PS> $PROFILE.AllUsersAllHosts C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1

オンラインでPowershellプロファイルをむ

https://riptutorial.com/ja/powershell/topic/5636/powershellプロファイル

https://riptutorial.com/ja/home 63

Page 83: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

24: Powershellモジュール

PowerShellバージョン2.0、はPowerShellモジュールをできます。 PowerShellモジュールは、ののセットをカプセルします。たとえば、さまざまなクラウドサービスをするベンダーのPowerShellモジュールがあります。また、ソーシャルメディアサービスとやりりし、Base64エンコーディング、Named PipeなどのなプログラミングタスクをするなPowerShellモジュールもあります。

モジュールは、コマンドエイリアス、、、クラスなどをすることができます。

Examples

モジュール・マニフェストの

@{ RootModule = 'MyCoolModule.psm1' ModuleVersion = '1.0' CompatiblePSEditions = @('Core') GUID = '6b42c995-67da-4139-be79-597a328056cc' Author = 'Bob Schmob' CompanyName = 'My Company' Copyright = '(c) 2017 Administrator. All rights reserved.' Description = 'It does cool stuff.' FunctionsToExport = @() CmdletsToExport = @() VariablesToExport = @() AliasesToExport = @() DscResourcesToExport = @() }

すべてのれたPowerShellモジュールにはモジュールマニフェストがあります。モジュールマニフェストには、PowerShellモジュールにするメタデータがまれているだけで、モジュールののはされていません。

マニフェストファイルは、 .psd1をむ.psd1ファイルをつPowerShellスクリプトファイルです。 PowerShellがしくPowerShellモジュールファイルとしてするためには、マニフェストのHashTableにのキーがまれているがあります。

のは、モジュールマニフェストをするなHashTableキーのリストをしていますが、にもあります。 New-ModuleManifestコマンドは、しいモジュールマニフェストスケルトンをするのにちます。

なモジュールの

function Add {

https://riptutorial.com/ja/home 64

Page 84: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

[CmdletBinding()] param ( [int] $x , [int] $y ) return $x + $y } Export-ModuleMember -Function Add

これは、PowerShellスクリプトモジュールファイルののなです。このファイルはMyCoolModule.psm1とばれ、モジュールマニフェスト.psd1ファイルからされます。 Export-ModuleMemberコマンドをすると、モジュールのどのをモジュールのユーザーに「エクスポートする」、またはするかをできます。のはのみであり、されるべきではないため、 Export-ModuleMemberびしではされます。

モジュールからののエクスポート

$FirstName = 'Bob' Export-ModuleMember -Variable FirstName

をモジュールからExport-ModuleMemberするには、 Export-ModuleMemberコマンドを-Variableパラメータとともに-Variableます。ただし、がにモジュールマニフェスト.psd1ファイルにエクスポートされていない、はモジュールコンシューマにはされません。モジュールのマニフェストを "ゲートキーパー"のようにえてください。またはがモジュールマニフェストでされていないは、モジュールにはされません。

をエクスポートすることは、クラスのフィールドをパブリックにすることにています。それはおめできません。フィールドをするとフィールドをするをするがよいでしょう。

PowerShellモジュールの

1つの.psm1 PowerShellスクリプトモジュールファイルにすべてのをするのではなく、をのファイルにしたいがあります。これらのファイルは、スクリプトモジュールファイルからドットソースできます。スクリプトモジュールファイルは、に.psm1ファイルのであるかのようにわれます。

このモジュールのディレクトリをえてみましょう

\MyCoolModule \Functions Function1.ps1 Function2.ps1 Function3.ps1 MyCoolModule.psd1 MyCoolModule.psm1

MyCoolModule.psm1ファイルにのコードをできます。

https://riptutorial.com/ja/home 65

Page 85: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Get-ChildItem -Path $PSScriptRoot\Functions | ForEach-Object -Process { . $PSItem.FullName }

これにより、々のファイルが.psm1モジュールファイルにドットソースされます。

モジュールの

PowerShellは、$ EnvPSModulepathにリストされているディレクトリのモジュールをします。

fooというフォルダにfooというモジュールが、でされるImport-Module foo

そのフォルダで、PowerShellはモジュールマニフェストfoo.psd1、モジュールファイルfoo.psm1

、DLLfoo.dllをします。

モジュールメンバーの

デフォルトでは、モジュールでされているのみがモジュールのにされます。いえると、モジュールでとエイリアスをすると、モジュールのコードではできなくなります。

このをオーバーライドするには、 Export-ModuleMemberコマンドレットをします。これには、 -Function 、 -Variable 、および-Aliasというパラメータがあり、エクスポートするメンバーをにできます。

Export-ModuleMemberをすると、しただけがされることにすることがです。

オンラインでPowershellモジュールをむ https://riptutorial.com/ja/powershell/topic/8734/powershell

モジュール

https://riptutorial.com/ja/home 66

Page 86: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

25: Powershellリモートabout_Remote•about_RemoteFAQ•about_Remoteトラブルシューティング•

Examples

PowerShell Remotingの

PowerShellリモーティングは、リモートでするサーバーでににするがあります。

Enable-PSRemoting -Force

このコマンドはのをいます。

のタスクをするSet-WSManQuickConfigコマンドレットをします。•

WinRMサービスをします。•

WinRMサービスのスタートアップのをにします。•

のIPアドレスでをけれるリスナーをしますしない。•

WS-Managementのファイアウォールをにします。•

Microsoft.PowerShellおよびMicrosoft.PowerShell.Workflowセッションがされていないは、します。

64ビットコンピュータにMicrosoft.PowerShell32セッションがされていないは、します。•

すべてのセッションをにします。•すべてのセッションのセキュリティをして、リモートアクセスをします。•のをにするために、WinRMサービスをします。•

ドメインのののみADドメインのサーバーの、PSリモートはKerberos 'Default'またはNTLM 'Negotiate'をしてわれます。ドメインのサーバーへのリモートアクセスをするは、2つのがあります。

HTTPSがをしたWSManをするか、ベースラインでをするをにするか64エンコードにプレーンテキストとじですのでしてください。

どちらのでも、リモートシステムをWSManのできるホストリストにするがあります。

Set-Item WSMan:\localhost\Service\AllowUnencrypted $true

https://riptutorial.com/ja/home 67

Page 87: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

そして、あなたからしたいコンピュータで、あなたがにしているコンピュータをすることをえなければなりません。

Set-Item WSMan:\localhost\Client\TrustedHosts '192.168.1.1,192.168.1.2'

Set-Item WSMan:\localhost\Client\TrustedHosts *.contoso.com

Set-Item WSMan:\localhost\Client\TrustedHosts *

するでアドレスされたコンピュータをするようにクライアントにするがありますたとえば、IPでするは、ホストではなくIPをするがあります

PowerShellでリモートサーバーにする

ローカルコンピュータのをする

Enter-PSSession 192.168.1.1

リモートコンピュータでののをめるプロンプト

Enter-PSSession 192.168.1.1 -Credential $(Get-Credential)

リモートコンピュータでコマンドをする

PowershellリモーティングがになったらEnable-PSRemotingリモートコンピュータでのようにコマンドをできます。

Invoke-Command -ComputerName "RemoteComputerName" -ScriptBlock { Write host "Remote Computer Name: $ENV:ComputerName" }

のメソッドは、セッションをし、コマンドまたはスクリプトブロックがしたにそれをじます。

セッションをいたままにしておき、でのコマンドをするには、まずリモートセッションをするがあります。

$Session = New-PSSession -ComputerName "RemoteComputerName"

に、リモートコンピュータでコマンドをびすたびに、このセッションをできます。

Invoke-Command -Session $Session -ScriptBlock { Write host "Remote Computer Name: $ENV:ComputerName" } Invoke-Command -Session $Session -ScriptBlock { Get-Date }

https://riptutorial.com/ja/home 68

Page 88: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

なるをするがあるは、 -Credentialパラメータをしてすることができます。

$Cred = Get-Credential Invoke-Command -Session $Session -Credential $Cred -ScriptBlock {...}

リモーティングシリアルのリモーティングは、リモートシステムのPowerShellオブジェクトをシリアルし、リモートセッションのにそれらをシリアルします。つまり、トランスポートにXMLにされ、すべてのメソッドがわれます。

$output = Invoke-Command -Session $Session -ScriptBlock { Get-WmiObject -Class win32_printer } $output | Get-Member -MemberType Method TypeName: Deserialized.System.Management.ManagementObject#root\cimv2\Win32_Printer Name MemberType Definition ---- ---------- ---------- GetType Method type GetType() ToString Method string ToString(), string ToString(string format, System.IFormatProvi...

のPSオブジェクトのメソッドはありますが、

Get-WmiObject -Class win32_printer | Get-Member -MemberType Method TypeName: System.Management.ManagementObject#root\cimv2\Win32_Printer Name MemberType Definition ---- ---------- ---------- CancelAllJobs Method System.Management.ManagementBaseObject CancelAllJobs() GetSecurityDescriptor Method System.Management.ManagementBaseObject GetSecurityDescriptor() Pause Method System.Management.ManagementBaseObject Pause() PrintTestPage Method System.Management.ManagementBaseObject PrintTestPage() RenamePrinter Method System.Management.ManagementBaseObject RenamePrinter(System.String NewPrinterName) Reset Method System.Management.ManagementBaseObject Reset() Resume Method System.Management.ManagementBaseObject Resume() SetDefaultPrinter Method System.Management.ManagementBaseObject SetDefaultPrinter() SetPowerState Method System.Management.ManagementBaseObject SetPowerState(System.UInt16 PowerState, System.String Time) SetSecurityDescriptor Method System.Management.ManagementBaseObject SetSecurityDescriptor(System.Management.ManagementObject#Win32_SecurityDescriptor Descriptor)

https://riptutorial.com/ja/home 69

Page 89: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

のをリモートスクリプティングブロックのパラメータとしてするには、 Invoke-Command ArgumentListパラメータをするか、 $Using:$Using:ます。

のないパラメータScriptblockにされたでArgumentListをう

$servicesToShow = "service1" $fileName = "C:\temp\servicestatus.csv" Invoke-Command -Session $session -ArgumentList $servicesToShow,$fileName -ScriptBlock { Write-Host "Calling script block remotely with $($Args.Count)" Get-Service -Name $args[0] Remove-Item -Path $args[1] -ErrorAction SilentlyContinue -Force }

きパラメータでのArgumentList

$servicesToShow = "service1" $fileName = "C:\temp\servicestatus.csv" Invoke-Command -Session $session -ArgumentList $servicesToShow,$fileName -ScriptBlock { Param($serviceToShowInRemoteSession,$fileToDelete) Write-Host "Calling script block remotely with $($Args.Count)" Get-Service -Name $serviceToShowInRemoteSession Remove-Item -Path $fileToDelete -ErrorAction SilentlyContinue -Force }

$Using:

$servicesToShow = "service1" $fileName = "C:\temp\servicestatus.csv" Invoke-Command -Session $session -ScriptBlock { Get-Service $Using:servicesToShow Remove-Item -Path $fileName -ErrorAction SilentlyContinue -Force }

PSSessionsをにクリーンアップするためのベストプラクティス

New-PSsessionコマンドレットをしてリモートセッションをすると、のPowerShellセッションがするまでPSSessionがされます。 PSSessionとするすべてのリソースは、のPowerShellセッションがするまで、ききされることをします。

のアクティブなPSSessionsは、に1つのPowerShellセッションでのPSSessionsをするまたはリンクされたスクリプトの、リソースのPSSessionsになります。

PSSessionがににすることをおPSSessionします。 [1]

のコードテンプレートは、のをするためにtry-catch-finallyしています。エラーとなをみわせて、されたPSSessionsがにすべてされるようにします。

https://riptutorial.com/ja/home 70

Page 90: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

try { $session = New-PSsession -Computername "RemoteMachineName" Invoke-Command -Session $session -ScriptBlock {write-host "This is running on $ENV:ComputerName"} } catch { Write-Output "ERROR: $_" } finally { if ($session) { Remove-PSSession $session } }

[1] https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/new-pssession

オンラインでPowershellリモートをむ https://riptutorial.com/ja/powershell/topic/3087/powershellリモート

https://riptutorial.com/ja/home 71

Page 91: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

26: PowerShellワークフロー

PowerShell Workflowは、PowerShellバージョン3.0からされたです。ワークフローはPowerShell

とよくていますが、PowerShellエンジンではなくWindows Workflow Foundationでされます。

ワークフローエンジンには、いくつかのユニークな「out of box」がまれています。にジョブのがあります。

PowerShell Workflowは、PowerShell Desktop EditionのMicrosoft Windowsプラットフォームでのみサポートされています。 Linux、Mac、およびWindowsでサポートされているPowerShell Core

Editionは、PowerShell Workflowをサポートしていません。

PowerShell Workflowをオーサリングするは、ワークフローがコマンドレットではなくアクティビティをびすことにしてください。 PowerShellワークフローからコマンドレットをびすことはできますが、ワークフローエンジンはInlineScriptアクティビティでコマンドレットのびしをにラップします。 PowerShellコードをするInlineScriptアクティビティでコードをにInlineScriptこともできます。デフォルトでは、 InlineScriptアクティビティはのプロセスでされ、びしのワークフローにがされます。

Examples

なワークフローの

workflow DoSomeWork { Get-Process -Name notepad | Stop-Process }

これはPowerShell Workflowのなです。

パラメータをしたワークフロー

PowerShellとに、ワークフローはパラメータをけれることができます。パラメーターは、オプションで、などののデータにバインドすることができます。パラメーターparamして、ワークフローのにパラメーターのブロックをします。

workflow DoSomeWork { param ( [string[]] $ComputerName ) Get-Process -ComputerName $ComputerName } DoSomeWork -ComputerName server01, server02, server03

https://riptutorial.com/ja/home 72

Page 92: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

バックグラウンドジョブとしてワークフローをする

PowerShellワークフローには、にバックグラウンドジョブとしてするがわっています。ワークフローをPowerShellのバックグラウンドジョブとしてびすには、ワークフローをびすときに-AsJob

パラメータをします。

workflow DoSomeWork { Get-Process -ComputerName server01 Get-Process -ComputerName server02 Get-Process -ComputerName server03 } DoSomeWork -AsJob

ワークフローへのブロックの

workflow DoSomeWork { parallel { Get-Process -ComputerName server01 Get-Process -ComputerName server02 Get-Process -ComputerName server03 } }

PowerShell Workflowのユニークなの1つは、アクティビティのブロックをしてするです。このをするには、ワークフローでparallelキーワードをします。

ワークフローアクティビティをしてびすと、ワークフローのパフォーマンスがするがあります。

オンラインでPowerShellワークフローをむ

https://riptutorial.com/ja/powershell/topic/8745/powershellワークフロー

https://riptutorial.com/ja/home 73

Page 93: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

27: PowerShell

はにきのコードブロックです。をびすと、そののスクリプトブロックがされます。これは、りてたをつPowerShellステートメントのです。をするときは、をします。これは、りしのタスクにりむときにをするです。 PowerShellは3つのにかれていますキーワード 'Function'、、にスクリプトブロックをむペイロードcurly /スタイルのでまれています。

Examples

パラメータなしのな

これは、をすのです。このでは、にをするステートメントでがびされます。こののは、のりです。

function Get-Greeting{ "Hello World" } # Invoking the function $greeting = Get-Greeting # demonstrate output $greeting Get-Greeting

functionはのコードをfunctionします。

Get-Greetingはのです。スクリプトでをするがあるときは、をでびすことでをびすことができます。

{ ... }は、によってされるスクリプトブロックです。

のコードがISEでされた、はのようになります。

Hello World Hello World

パラメータ

は、paramブロックをしてパラメータでできます。

function Write-Greeting { param( [Parameter(Mandatory,Position=0)]

https://riptutorial.com/ja/home 74

Page 94: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

[String]$name, [Parameter(Mandatory,Position=1)] [Int]$age ) "Hello $name, you are $age years old." }

または、なのをします。

function Write-Greeting ($name, $age) { "Hello $name, you are $age years old." }

いずれのタイプのパラメーターでも、キャストパラメーターはありません。

SFSは、paramブロックとしてにされたしかっていません。 でされるパラメータをすることはできますが、 パラメータのをしたり、 パラメータのをしたり、 [CmdletBinding()]をSFSとともにめることはできませんこれはなリストです。

は、きまたはきのパラメーターでびすことができます。

びしのパラメーターのは、ヘッダーののデフォルトとするか、 Positionパラメーターをしてできますののを。

$greeting = Write-Greeting "Jim" 82

あるいは、このはきパラメータでびすことができます

$greeting = Write-Greeting -name "Bob" -age 82

パラメータ

へのパラメータは、としてマークすることができます

function Get-Greeting{ param ( [Parameter(Mandatory=$true)]$name ) "Hello World $name" }

がなしでびされた、コマンドラインはのをめます

$greeting = Get-Greeting cmdlet Get-Greeting at command pipeline position 1 Supply values for the following parameters: name:

https://riptutorial.com/ja/home 75

Page 95: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

これはPowershell ISEからのなスニペットのコピーです。に、これはPowerShellのなでできるくのもののテンプレートです。すべきポイント

get-help integration - のには、get-helpコマンドレットによってみられるようにされたコメントブロックがまれています。ブロックは、にじてにすることができます。

cmdletbinding - はコマンドレットのようにします•

パラメーター•パラメータセット•

<# .Synopsis Short description .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES General notes .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> function Verb-Noun { [CmdletBinding(DefaultParameterSetName='Parameter Set 1', SupportsShouldProcess=$true, PositionalBinding=$false, HelpUri = 'http://www.microsoft.com/', ConfirmImpact='Medium')] [Alias()] [OutputType([String])] Param ( # Param1 help description [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidateCount(0,5)] [ValidateSet("sun", "moon", "earth")] [Alias("p1")] $Param1,

https://riptutorial.com/ja/home 76

Page 96: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# Param2 help description [Parameter(ParameterSetName='Parameter Set 1')] [AllowNull()] [AllowEmptyCollection()] [AllowEmptyString()] [ValidateScript({$true})] [ValidateRange(0,5)] [int] $Param2, # Param3 help description [Parameter(ParameterSetName='Another Parameter Set')] [ValidatePattern("[a-z]*")] [ValidateLength(0,15)] [String] $Param3 ) Begin { } Process { if ($pscmdlet.ShouldProcess("Target", "Operation")) { } } End { } }

パラメータ

PowerShellでは、パラメータのをするさまざまながあります。

パラメータをするためのやスクリプトにコードをするのではなく、ながされた、これらのParameterAttributesがスローされます。

ValidateSet

によっては、パラメータがけれることができるなをするがあります。スクリプトやの$Colorパラメータに、、だけをしたいとします。

ValidateSetパラメータをしてこれをすることができます。このをするときにタブのをするというのがありますによっては。

param( [ValidateSet('red','green','blue',IgnoreCase)] [string]$Color )

とのをにするには、 IgnoreCaseをすることもできます。

https://riptutorial.com/ja/home 77

Page 97: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

ValidateRange

このパラメータのでは、とのInt32がされ、そのにパラメータがです。

param( [ValidateRange(0,120)] [Int]$Age )

ValidatePattern

このパラメータのは、されたパターンにするパラメータをけれます。

param( [ValidatePattern("\w{4-6}\d{2}")] [string]$UserName )

ValidateLength

このパラメータは、されたのさをテストします。

param( [ValidateLength(0,15)] [String]$PhoneNumber )

ValidateCount

このパラメータは、されたの、たとえばのをテストします。

param( [ValidateCount(1,5)] [String[]]$ComputerName )

ValidateScript

に、ValidateScriptメソッドはにで、スクリプトブロックをとり、されたをすために$ _をしてします。が$ trueのをとしてむの、をします。

これは、ファイルがするかどうかをテストするためにできます

param( [ValidateScript({Test-Path $_})] [IO.FileInfo]$Path

https://riptutorial.com/ja/home 78

Page 98: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

)

ユーザーがADにすることをするには

param( [ValidateScript({Get-ADUser $_})] [String]$UserName )

そして、あなたがくことができるのほとんどのものonelinersにされていないので

param( [ValidateScript({ $AnHourAgo = (Get-Date).AddHours(-1) if ($_ -lt $AnHourAgo.AddMinutes(5) -and $_ -gt $AnHourAgo.AddMinutes(-5)) { $true } else { throw "That's not within five minutes. Try again." } })] [String]$TimeAboutAnHourAgo )

オンラインでPowerShellをむ https://riptutorial.com/ja/powershell/topic/1673/powershell

https://riptutorial.com/ja/home 79

Page 99: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

28: Psake

タスク - ビルドスクリプトのステップをするmain•

Depends - のステップがするものをするプロパティ•

default - タスクがされていないにされるデフォルトタスクがにするがあります•

FormatTaskName - ステップをウィンドウにするをします。•

psakeは、PowerShellでかれたビルドオートメーションツールであり、RakeRuby makeとBake

Boo makeにインスパイアされています。パターンをしてビルドをするためにされます。ドキュメントはこちらからできます

Examples

Task Rebuild -Depends Clean, Build { "Rebuild" } Task Build { "Build" } Task Clean { "Clean" } Task default -Depends Build

FormatTaskNameの

# Will display task as: # -------- Rebuild -------- # -------- Build -------- FormatTaskName "-------- {0} --------" # will display tasks in yellow colour: # Running Rebuild FormatTaskName { param($taskName) "Running $taskName" - foregroundcolor yellow } Task Rebuild -Depends Clean, Build { "Rebuild" } Task Build { "Build" }

https://riptutorial.com/ja/home 80

Page 100: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Task Clean { "Clean" } Task default -Depends Build

タスクをきでする

propreties { $isOk = $false } # By default the Build task won't run, unless there is a param $true Task Build -precondition { return $isOk } { "Build" } Task Clean { "Clean" } Task default -Depends Build

ContinueOnError

Task Build -depends Clean { "Build" } Task Clean -ContinueOnError { "Clean" throw "throw on purpose, but the task will continue to run" } Task default -Depends Build

オンラインでPsakeをむ https://riptutorial.com/ja/powershell/topic/5019/psake

https://riptutorial.com/ja/home 81

Page 101: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

29: PSScriptAnalyzer - PowerShellスクリプトアナライザ

PSScriptAnalyzer、 https://github.com/PowerShell/PSScriptAnalyzerは、Windows PowerShellモジュールとスクリプトのコードチェッカーです。 PSScriptAnalyzerは、PowerShellチームおよびコミュニティによってされたPowerShellのベストプラクティスにづいてのルールをすることにより、Windows PowerShellコードのをチェックします。 DiagnosticResultsエラーとをしてなコードのをユーザーにし、のためのをします。

PS> Install-Module -Name PSScriptAnalyzer

Get-ScriptAnalyzerRule [-CustomizedRulePath <string[]>] [-Name <string[]>] [-Severity <string[]>] [<CommonParameters>]

1.

Invoke-ScriptAnalyzer [-Path] <string> [-CustomizedRulePath <string[]>] [-ExcludeRule <string[]>] [-IncludeRule<string[]>] [-Severity <string[]>] [-Recurse] [-SuppressedOnly] [<CommonParameters>]

2.

Examples

みみプリセットルールセットをしたスクリプトの

ScriptAnalyzerには、スクリプトをするためのプリセットルールがみまれています。 PSGallery 、 DSC 、 CodeFormattingなどがありCodeFormatting 。それらはのようにできます

PowerShell Galleryのルール

PowerShell Galleryルールをするには、のコマンドをします。

Invoke-ScriptAnalyzer -Path /path/to/module/ -Settings PSGallery -Recurse

DSCルール

DSCルールをするには、のコマンドをします。

Invoke-ScriptAnalyzer -Path /path/to/module/ -Settings DSC -Recurse

コードのの

コードのルールをするには、のコマンドをします。

Invoke-ScriptAnalyzer -Path /path/to/module/ -Settings CodeFormatting -Recurse

https://riptutorial.com/ja/home 82

Page 102: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

すべてのビルトインルールにするスクリプトの

スクリプト・アナライザをのスクリプト・ファイルにしてするには、のコマンドをします。

Invoke-ScriptAnalyzer -Path myscript.ps1

これにより、みみルールごとにスクリプトがされます。スクリプトがにきい、やエラーがするがあります。

スクリプトアナライザをディレクトリにしてするには、するスクリプト、モジュール、およびDSCファイルをむフォルダをします。サブディレクトリでファイルをしてするは、Recurseパラメータをします。

Invoke-ScriptAnalyzer -Path . -Recurse

すべてのビルトインルールをする

みみルールをすべてするには、のようにします。

Get-ScriptAnalyzerRule

オンラインでPSScriptAnalyzer - PowerShellスクリプトアナライザをむ

https://riptutorial.com/ja/powershell/topic/9619/psscriptanalyzer-----powershellスクリプトアナライザ

https://riptutorial.com/ja/home 83

Page 103: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

30: RESTful APIとの

RESTは、Representational State Transferには「ReST」とかれていますのです。これは、ステートレスのクライアントサーバー、キャッシュなプロトコルにし、ほとんどがHTTPプロトコルがされます。に、で、があり、スケーラビリティのいWebサービスをするためにされます。 REST

にづくサービスはRESTfulなサービスとばれ、そのためにされているAPIはRESTfulなAPIです。 PowerShellでは、 Invoke-RestMethodがそれらをするためにされます。

Examples

Slack.comのWebhookをする

よりなデータをするためのペイロードをする

$Payload = @{ text="test string"; username="testuser" }

ConvertTo-JsonコマンドレットとInvoke-RestMethodをしてびしをする

Invoke-RestMethod -Uri "https://hooks.slack.com/services/yourwebhookstring" -Method Post -Body (ConvertTo-Json $Payload)

hipChatへのメッセージ

$params = @{ Uri = "https://your.hipchat.com/v2/room/934419/notification?auth_token=???" Method = "POST" Body = @{ color = 'yellow' message = "This is a test message!" notify = $false message_format = "text" } | ConvertTo-Json ContentType = 'application/json' } Invoke-RestMethod @params

PowerShellオブジェクトでRESTをして々のデータをおよびする

RESTデータをし、PowerShellオブジェクトにします。

$Post = Invoke-RestMethod -Uri "http://jsonplaceholder.typicode.com/posts/1"

https://riptutorial.com/ja/home 84

Page 104: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

データをする

$Post.title = "New Title"

RESTデータをします。

$Json = $Post | ConvertTo-Json Invoke-RestMethod -Method Put -Uri "http://jsonplaceholder.typicode.com/posts/1" -Body $Json -ContentType 'application/json'

PowerShellオブジェクトでRESTをしてくのアイテムをおよびPOSTする

RESTデータをし、PowerShellオブジェクトにします。

$Users = Invoke-RestMethod -Uri "http://jsonplaceholder.typicode.com/users"

データのくのをする

$Users[0].name = "John Smith" $Users[0].email = "[email protected]" $Users[1].name = "Jane Smith" $Users[1].email = "[email protected]"

すべてのRESTデータをPOSTします。

$Json = $Users | ConvertTo-Json Invoke-RestMethod -Method Post -Uri "http://jsonplaceholder.typicode.com/users" -Body $Json -ContentType 'application/json'

PowerShellでのRESTをしたアイテムの

するアイテムをしてします。

Invoke-RestMethod -Method Delete -Uri "http://jsonplaceholder.typicode.com/posts/1"

オンラインでRESTful APIとのをむ https://riptutorial.com/ja/powershell/topic/3869/restful-apiとの

https://riptutorial.com/ja/home 85

Page 105: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

31: SharePointモジュール

Examples

SharePointスナップインのみみ

SharePoint Snapinのロードは、のでうことができます。

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

これはPowerShellの64ビットでのみします。タイトルに「Windows PowerShellx86」とされたは、ったバージョンをしています。

スナップインがにみまれているは、のコードでエラーがします。をすると、なにのみロードされ、コマンドレット/でできます。

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Microsoft.SharePoint.PowerShell" }

また、SharePointシェルをすると、にスナップインがみまれます。

なすべてのSharePointコマンドレットのをするには、のコマンドをします。

Get-Command -Module Microsoft.SharePoint.PowerShell

サイトコレクションのすべてのリストをりしする

すべてのリストとアイテムをします。

$site = Get-SPSite -Identity https://mysharepointsite/sites/test foreach ($web in $site.AllWebs) { foreach ($list in $web.Lists) { # Prints list title and item count Write-Output "$($list.Title), Items: $($list.ItemCount)" } } $site.Dispose()

インストールされているすべてのをサイトコレクションでする

Get-SPFeature -Site https://mysharepointsite/sites/test

Get-SPFeatureは、Webスコープ -Web <WebUrl> 、ファームスコープ -Farm 、およびWebアプリケーションスコープ -WebApplication <WebAppUrl> ですることもできます。

https://riptutorial.com/ja/home 86

Page 106: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

サイトコレクションのすべてのしたをする

Get-SPFeatureののいは、スコープのないすべてのをつけることです。

Get-SPFeature -Site https://mysharepointsite/sites/test |? { $_.Scope -eq $null )

オンラインでSharePointモジュールをむ https://riptutorial.com/ja/powershell/topic/5147/sharepoint

モジュール

https://riptutorial.com/ja/home 87

Page 107: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

32: ShouldProcessの$ PSCmdlet.ShouldProcess "Target"•$ PSCmdlet.ShouldProcess "Target"、 "Action"•

パラメーター

パラメータ

ターゲット リソースがされています。

アクション されている。デフォルトはコマンドレットのです。

$PSCmdlet.ShouldProcess()はににメッセージをきみます。

PS> Invoke-MyCmdlet -Verbose VERBOSE: Performing the operation "Invoke-MyCmdlet" on target "Target of action"

Examples

コマンドレットに-WhatIfと-Confirmのサポートをする

function Invoke-MyCmdlet { [CmdletBinding(SupportsShouldProcess = $true)] param() # ... }

1つのでShouldProcessをする

if ($PSCmdlet.ShouldProcess("Target of action")) { # Do the thing }

-WhatIfをする

What if: Performing the action "Invoke-MyCmdlet" on target "Target of action"

-Confirmをする

Are you sure you want to perform this action? Performing operation "Invoke-MyCmdlet" on target "Target of action" [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

https://riptutorial.com/ja/home 88

Page 108: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

のでは、きロジックをトリガするをににできませんでした。

このでは、になるコマンドも-Confirmフラグをいています。

<# Restart-Win32Computer #> function Restart-Win32Computer { [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$computerName, [parameter(Mandatory=$true)] [string][ValidateSet("Restart","LogOff","Shutdown","PowerOff")] $action, [boolean]$force = $false ) BEGIN { # translate action to numeric value required by the method switch($action) { "Restart" { $_action = 2 break } "LogOff" { $_action = 0 break } "Shutdown" { $_action = 2 break } "PowerOff" { $_action = 8 break } } # to force, add 4 to the value if($force) { $_action += 4 } write-verbose "Action set to $action" } PROCESS { write-verbose "Attempting to connect to $computername" # this is how we support -whatif and -confirm # which are enabled by the SupportsShouldProcess # parameter in the cmdlet bindnig if($pscmdlet.ShouldProcess($computername)) { get-wmiobject win32_operatingsystem -computername $computername | invoke-wmimethod -name Win32Shutdown -argumentlist $_action

https://riptutorial.com/ja/home 89

Page 109: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

} } } #Usage: #This will only output a description of the actions that this command would execute if -WhatIf is removed. 'localhost','server1'| Restart-Win32Computer -action LogOff -whatif #This will request the permission of the caller to continue with this item. #Attention: in this example you will get two confirmation request because all cmdlets called by this cmdlet that also support ShouldProcess, will ask for their own confirmations... 'localhost','server1'| Restart-Win32Computer -action LogOff -Confirm

オンラインでShouldProcessのをむ https://riptutorial.com/ja/powershell/topic/1145/shouldprocess

https://riptutorial.com/ja/home 90

Page 110: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

33: URLエンコード/デコードデコードURLのでされるは、 RFC 2396、BによるURIの 。のために、ここにがあります

のは、URIをそのコンポーネントにするです。

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? 12 3 4 5 6 7 8 9

の2のは、みやすくするためのものです。それらは、のすなわち、ペアのかっこをします。にマッチしたを$とぶ。えば、のを

http://www.ics.uci.edu/pub/ietf/uri/#Related

のがします。

$1 = http: $2 = http $3 = //www.ics.uci.edu $4 = www.ics.uci.edu $5 = /pub/ietf/uri/ $6 = <undefined> $7 = <undefined> $8 = #Related $9 = Related

Examples

クイックスタートエンコーディング

$url1 = [uri]::EscapeDataString("http://test.com?test=my value") # url1: http%3A%2F%2Ftest.com%3Ftest%3Dmy%20value $url2 = [uri]::EscapeUriString("http://test.com?test=my value") # url2: http://test.com?test=my%20value # HttpUtility requires at least .NET 1.1 to be installed. $url3 = [System.Web.HttpUtility]::UrlEncode("http://test.com?test=my value") # url3: http%3a%2f%2ftest.com%3ftest%3dmy+value

HTTPUtilityにする 。

クイックスタートデコード

これらのでは、のクイックスタートエンコードセクションでしたをしています。

# url1: http%3A%2F%2Ftest.com%3Ftest%3Dmy%20value [uri]::UnescapeDataString($url1)

https://riptutorial.com/ja/home 91

Page 111: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# Returns: http://test.com?test=my value # url2: http://test.com?test=my%20value [uri]::UnescapeDataString($url2) # Returns: http://test.com?test=my value # url3: http%3a%2f%2ftest.com%3ftest%3dmy+value [uri]::UnescapeDataString($url3) # Returns: http://test.com?test=my+value # Note: There is no `[uri]::UnescapeUriString()`; # which makes sense since the `[uri]::UnescapeDataString()` # function handles everything it would handle plus more. # HttpUtility requires at least .NET 1.1 to be installed. # url1: http%3A%2F%2Ftest.com%3Ftest%3Dmy%20value [System.Web.HttpUtility]::UrlDecode($url1) # Returns: http://test.com?test=my value # HttpUtility requires at least .NET 1.1 to be installed. # url2: http://test.com?test=my%20value [System.Web.HttpUtility]::UrlDecode($url2) # Returns: http://test.com?test=my value # HttpUtility requires at least .NET 1.1 to be installed. # url3: http%3a%2f%2ftest.com%3ftest%3dmy+value [System.Web.HttpUtility]::UrlDecode($url3) # Returns: http://test.com?test=my value

HTTPUtilityにする 。

`[uri] :: EscapeDataString`でクエリをエンコードする

$scheme = 'https' $url_format = '{0}://example.vertigion.com/foos?{1}' $qs_data = @{ 'foo1'='bar1'; 'foo2'= 'complex;/?:@&=+$, bar''"'; 'complex;/?:@&=+$, foo''"'='bar2'; } [System.Collections.ArrayList] $qs_array = @() foreach ($qs in $qs_data.GetEnumerator()) { $qs_key = [uri]::EscapeDataString($qs.Name) $qs_value = [uri]::EscapeDataString($qs.Value) $qs_array.Add("${qs_key}=${qs_value}") | Out-Null } $url = $url_format -f @([uri]::"UriScheme${scheme}", ($qs_array -join '&'))

[uri]::EscapeDataString()をすると、アポストロフィ ' がエンコードされていないことが[uri]::EscapeDataString()ます。

https://example.vertigion.com/foos foo2 =3B2F3F3A40263D2B242C20bar '223B2F3F3A40263D2B242C 20foo '22 = bar2foo1 = bar1

https://riptutorial.com/ja/home 92

Page 112: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

`[System.Web.HttpUtility] :: UrlEncodeでクエリをエンコードする

$scheme = 'https' $url_format = '{0}://example.vertigion.com/foos?{1}' $qs_data = @{ 'foo1'='bar1'; 'foo2'= 'complex;/?:@&=+$, bar''"'; 'complex;/?:@&=+$, foo''"'='bar2'; } [System.Collections.ArrayList] $qs_array = @() foreach ($qs in $qs_data.GetEnumerator()) { $qs_key = [System.Web.HttpUtility]::UrlEncode($qs.Name) $qs_value = [System.Web.HttpUtility]::UrlEncode($qs.Value) $qs_array.Add("${qs_key}=${qs_value}") | Out-Null } $url = $url_format -f @([uri]::"UriScheme${scheme}", ($qs_array -join '&'))

[System.Web.HttpUtility]::UrlEncode()をすると、が%20わりにプラス + にわります。

https://example.vertigion.com/foos foo2 =3b2f3f3a40263d2b242c + bar27223b2f3f3a40263d2b242c + foo2722 = bar2foo1 = bar1

`[uri] :: UnescapeDataStringでURLをデコードする

[uri]::EscapeDataString()エンコード

まず、ので[uri]::EscapeDataString()でエンコードされたURLとクエリをデコードします

https://example.vertigion.com/foos foo2 =3B2F3F3A40263D2B242C20bar '223B2F3F3A40263D2B242C 20foo '22 = bar2foo1 = bar1

$url = 'https://example.vertigion.com/foos?foo2=complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20bar''%22&complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20foo''%22=bar2&foo1=bar1' $url_parts_regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?' # See Remarks if ($url -match $url_parts_regex) { $url_parts = @{ 'Scheme' = $Matches[2]; 'Server' = $Matches[4]; 'Path' = $Matches[5]; 'QueryString' = $Matches[7]; 'QueryStringParts' = @{} } foreach ($qs in $query_string.Split('&')) { $qs_key, $qs_value = $qs.Split('=') $url_parts.QueryStringParts.Add( [uri]::UnescapeDataString($qs_key), [uri]::UnescapeDataString($qs_value) ) | Out-Null } } else {

https://riptutorial.com/ja/home 93

Page 113: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Throw [System.Management.Automation.ParameterBindingException] "Invalid URL Supplied" }

これはあなたにる[hashtable]$url_partsます。これにしい なにスペースです。

PS > $url_parts Name Value ---- ----- Scheme https Path /foos Server example.vertigion.com QueryString foo2=complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20bar'%22&complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20foo'%22=bar2&foo1=bar1 QueryStringParts {foo2, complex;/?:@&=+$, foo'", foo1} PS > $url_parts.QueryStringParts Name Value ---- ----- foo2 complex;/?:@&=+$, bar'" complex;/?:@&=+$, foo'" bar2 foo1 bar1

[System.Web.HttpUtility]::UrlEncode()エンコードされます[System.Web.HttpUtility]::UrlEncode()

のでは、 [System.Web.HttpUtility]::UrlEncode()でエンコードされたURLとクエリをデコードします。

https://example.vertigion.com/foos foo2 =3b2f3f3a40263d2b242c + bar27223b2f3f3a40263d2b242c + foo2722 = bar2foo1 = bar1

$url = 'https://example.vertigion.com/foos?foo2=complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+bar%27%22&complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+foo%27%22=bar2&foo1=bar1' $url_parts_regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?' # See Remarks if ($url -match $url_parts_regex) { $url_parts = @{ 'Scheme' = $Matches[2]; 'Server' = $Matches[4]; 'Path' = $Matches[5]; 'QueryString' = $Matches[7]; 'QueryStringParts' = @{} } foreach ($qs in $query_string.Split('&')) { $qs_key, $qs_value = $qs.Split('=') $url_parts.QueryStringParts.Add( [uri]::UnescapeDataString($qs_key), [uri]::UnescapeDataString($qs_value) ) | Out-Null } } else { Throw [System.Management.Automation.ParameterBindingException] "Invalid URL Supplied"

https://riptutorial.com/ja/home 94

Page 114: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

}

これは、 [hashtable]$url_partsをします なのスペースは、のではプラス + 、2ではスペース 。

PS > $url_parts Name Value ---- ----- Scheme https Path /foos Server example.vertigion.com QueryString foo2=complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+bar%27%22&complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+foo%27%22=bar2&foo1=bar1 QueryStringParts {foo2, complex;/?:@&=+$, foo'", foo1} PS > $url_parts.QueryStringParts Name Value ---- ----- foo2 complex;/?:@&=+$, bar'" complex;/?:@&=+$, foo'" bar2 foo1 bar1

`[System.Web.HttpUtility] :: UrlDecodeでURLをデコードする

[uri]::EscapeDataString()エンコード

まず、ので[uri]::EscapeDataString()でエンコードされたURLとクエリをデコードします

https://example.vertigion.com/foos foo2 =3B2F3F3A40263D2B242C20bar '223B2F3F3A40263D2B242C 20foo '22 = bar2foo1 = bar1

$url = 'https://example.vertigion.com/foos?foo2=complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20bar''%22&complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20foo''%22=bar2&foo1=bar1' $url_parts_regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?' # See Remarks if ($url -match $url_parts_regex) { $url_parts = @{ 'Scheme' = $Matches[2]; 'Server' = $Matches[4]; 'Path' = $Matches[5]; 'QueryString' = $Matches[7]; 'QueryStringParts' = @{} } foreach ($qs in $query_string.Split('&')) { $qs_key, $qs_value = $qs.Split('=') $url_parts.QueryStringParts.Add( [System.Web.HttpUtility]::UrlDecode($qs_key), [System.Web.HttpUtility]::UrlDecode($qs_value) ) | Out-Null } } else {

https://riptutorial.com/ja/home 95

Page 115: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Throw [System.Management.Automation.ParameterBindingException] "Invalid URL Supplied" }

これはあなたにる[hashtable]$url_partsます。これにしい なにスペースです。

PS > $url_parts Name Value ---- ----- Scheme https Path /foos Server example.vertigion.com QueryString foo2=complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20bar'%22&complex%3B%2F%3F%3A%40%26%3D%2B%24%2C%20foo'%22=bar2&foo1=bar1 QueryStringParts {foo2, complex;/?:@&=+$, foo'", foo1} PS > $url_parts.QueryStringParts Name Value ---- ----- foo2 complex;/?:@&=+$, bar'" complex;/?:@&=+$, foo'" bar2 foo1 bar1

[System.Web.HttpUtility]::UrlEncode()エンコードされます[System.Web.HttpUtility]::UrlEncode()

のでは、 [System.Web.HttpUtility]::UrlEncode()でエンコードされたURLとクエリをデコードします。

https://example.vertigion.com/foos foo2 =3b2f3f3a40263d2b242c + bar27223b2f3f3a40263d2b242c + foo2722 = bar2foo1 = bar1

$url = 'https://example.vertigion.com/foos?foo2=complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+bar%27%22&complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+foo%27%22=bar2&foo1=bar1' $url_parts_regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?' # See Remarks if ($url -match $url_parts_regex) { $url_parts = @{ 'Scheme' = $Matches[2]; 'Server' = $Matches[4]; 'Path' = $Matches[5]; 'QueryString' = $Matches[7]; 'QueryStringParts' = @{} } foreach ($qs in $query_string.Split('&')) { $qs_key, $qs_value = $qs.Split('=') $url_parts.QueryStringParts.Add( [System.Web.HttpUtility]::UrlDecode($qs_key), [System.Web.HttpUtility]::UrlDecode($qs_value) ) | Out-Null } } else { Throw [System.Management.Automation.ParameterBindingException] "Invalid URL Supplied"

https://riptutorial.com/ja/home 96

Page 116: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

}

これはあなたにる[hashtable]$url_partsます。これにしい なにスペースです。

PS > $url_parts Name Value ---- ----- Scheme https Path /foos Server example.vertigion.com QueryString foo2=complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+bar%27%22&complex%3b%2f%3f%3a%40%26%3d%2b%24%2c+foo%27%22=bar2&foo1=bar1 QueryStringParts {foo2, complex;/?:@&=+$, foo'", foo1} PS > $url_parts.QueryStringParts Name Value ---- ----- foo2 complex;/?:@&=+$, bar'" complex;/?:@&=+$, foo'" bar2 foo1 bar1

オンラインでURLエンコード/デコードをむ https://riptutorial.com/ja/powershell/topic/7352/urlエンコード-デコード

https://riptutorial.com/ja/home 97

Page 117: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

34: WMIとCIM

CIMとWMI

PowerShell 3.0、PowerShell、WMI、およびCIMでクラスをするには、2つのがあります。 PowerShell 1.0および2.0では、WIMモジュールのみがサポートされました.WIMモジュールは、しくされたCIMモジュールよりもれています。 PowerShellののリリースでは、WMI-cmdletsがされます。

CIMモジュールとWMIモジュールの

CIM-cmdlet WMI-cmdlet それはですか

Get-CimInstance Get-WmiObject クラスのCIM / WMIオブジェクトをする

Invoke-CimMethodInvoke-WmiMethod

CIM / WMIクラスメソッドをびす

Register-CimIndicationEvent

Register-WmiEvent

CIM / WMIクラスのイベントをする

Remove-CimInstanceRemove-WmiObject

CIM / WMIオブジェクトをする

Set-CimInstanceSet-WmiInstance

CIM / WMIオブジェクトの/

Get-CimAssociatedInstance

N / Aするインスタンスリンクされたオブジェクト/クラスをする

Get-CimClassGet-WmiObject -List

CIM / WMIクラスのリスト

New-CimInstance N / A しいCIMオブジェクトをする

Get-CimSession N / A CIMセッションをする

New-CimSession N / A しいCIMセッションをする

New-CimSessionOption N / Aセッションオプションをしてオブジェクトをします。プロトコル、エンコーディング、をにするなど New-CimSessionでする

Remove-CimSession N / A CIMセッションの/

https://riptutorial.com/ja/home 98

Page 118: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

そののリソースWindows PowerShellでCIMまたはWMIをするがありますか @ Hey、Scripting Guyブログ

Examples

オブジェクトのクエリ

CIM / WMIは、デバイスのまたはをするためにもにされます。 PowerShellでは、これらのクラスとインスタンスにアクセスするのがありますが、もなはGet-CimInstance CIMコマンドレットまたはGet-WmiObject WMIコマンドレットをするです。

CIMクラスのすべてのオブジェクトをするクラスのすべてのインスタンスをリストすることができます。

3.0

CIM

> Get-CimInstance -ClassName Win32_Process ProcessId Name HandleCount WorkingSetSize VirtualSize --------- ---- ----------- -------------- ----------- 0 System Idle Process 0 4096 65536 4 System 1459 32768 3563520 480 Secure System 0 3731456 0 484 smss.exe 52 372736 2199029891072 .... ....

WMI

Get-WmiObject -Class Win32_Process

フィルタのフィルタをして、CIM / WMIクラスののインスタンスのみをすることができます。フィルタは、 WQL デフォルトまたはCQLAdd -QueryDialect CQL をしてされます。 -Filterは、なWQL / CQLクエリのWHEREをします。

3.0

CIM

https://riptutorial.com/ja/home 99

Page 119: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Get-CimInstance -ClassName Win32_Process -Filter "Name = 'powershell.exe'" ProcessId Name HandleCount WorkingSetSize VirtualSize --------- ---- ----------- -------------- ----------- 4800 powershell.exe 676 88305664 2199697199104

WMI

Get-WmiObject -Class Win32_Process -Filter "Name = 'powershell.exe'" ... Caption : powershell.exe CommandLine : "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" CreationClassName : Win32_Process CreationDate : 20160913184324.393887+120 CSCreationClassName : Win32_ComputerSystem CSName : STACKOVERFLOW-PC Description : powershell.exe ExecutablePath : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ExecutionState : Handle : 4800 HandleCount : 673 ....

WQLクエリをするまた、WQL / CQLクエリをして、インスタンスのクエリとフィルタリングをうこともできます。

3.0

CIM

Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE Name = 'powershell.exe'" ProcessId Name HandleCount WorkingSetSize VirtualSize --------- ---- ----------- -------------- ----------- 4800 powershell.exe 673 88387584 2199696674816

ののオブジェクトのクエリ

3.0

CIM

> Get-CimInstance -Namespace "root/SecurityCenter2" -ClassName AntiVirusProduct displayName : Windows Defender instanceGuid : {D68DDC3A-831F-4fae-9E44-DA132C1ACF46} pathToSignedProductExe : %ProgramFiles%\Windows Defender\MSASCui.exe pathToSignedReportingExe : %ProgramFiles%\Windows Defender\MsMpeng.exe productState : 397568 timestamp : Fri, 09 Sep 2016 21:26:41 GMT

https://riptutorial.com/ja/home 100

Page 120: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PSComputerName :

WMI

> Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct __GENUS : 2 __CLASS : AntiVirusProduct __SUPERCLASS : __DYNASTY : AntiVirusProduct __RELPATH : AntiVirusProduct.instanceGuid="{D68DDC3A-831F-4fae-9E44-DA132C1ACF46}" __PROPERTY_COUNT : 6 __DERIVATION : {} __SERVER : STACKOVERFLOW-PC __NAMESPACE : ROOT\SecurityCenter2 __PATH : \\STACKOVERFLOW-PC\ROOT\SecurityCenter2:AntiVirusProduct.instanceGuid="{D68DDC3A-831F-4fae-9E44-DA132C1ACF46}" displayName : Windows Defender instanceGuid : {D68DDC3A-831F-4fae-9E44-DA132C1ACF46} pathToSignedProductExe : %ProgramFiles%\Windows Defender\MSASCui.exe pathToSignedReportingExe : %ProgramFiles%\Windows Defender\MsMpeng.exe productState : 397568 timestamp : Fri, 09 Sep 2016 21:26:41 GMT PSComputerName : STACKOVERFLOW-PC

クラスと

CIMとWMIには、のにかれているくのクラスがあります。 Windowsのもなそしてデフォルトのはroot/cimv2です。 righクラスをつけるには、allまたはsearchをリストするとです。

なクラスをするコンピュータのデフォルトネームスペース root/cimv2 にあるなクラスをすべてできます。

3.0

CIM

Get-CimClass

WMI

Get-WmiObject -List

クラスをするワイルドカードをしてのクラスをすることができます。 Ex processというをむクラスをつける。

https://riptutorial.com/ja/home 101

Page 121: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

3.0

CIM

> Get-CimClass -ClassName "*Process*" NameSpace: ROOT/CIMV2 CimClassName CimClassMethods CimClassProperties ------------ --------------- ------------------ Win32_ProcessTrace {} {SECURITY_DESCRIPTOR, TIME_CREATED, ParentProcessID, ProcessID...} Win32_ProcessStartTrace {} {SECURITY_DESCRIPTOR, TIME_CREATED, ParentProcessID, ProcessID...} Win32_ProcessStopTrace {} {SECURITY_DESCRIPTOR, TIME_CREATED, ParentProcessID, ProcessID...} CIM_Process {} {Caption, Description, InstallDate, Name...} Win32_Process {Create, Terminat... {Caption, Description, InstallDate, Name...} CIM_Processor {SetPowerState, R... {Caption, Description, InstallDate, Name...} Win32_Processor {SetPowerState, R... {Caption, Description, InstallDate, Name...} ...

WMI

Get-WmiObject -List -Class "*Process*"

なるのクラスをするルートはにrootとばれます。 -NameSpaceパラメーターをして、のにクラスをリストすることができます。

3.0

CIM

> Get-CimClass -Namespace "root/SecurityCenter2" NameSpace: ROOT/SecurityCenter2 CimClassName CimClassMethods CimClassProperties ------------ --------------- ------------------ .... AntiSpywareProduct {} {displayName, instanceGuid, pathToSignedProductExe, pathToSignedReportingE... AntiVirusProduct {} {displayName, instanceGuid, pathToSignedProductExe, pathToSignedReportingE... FirewallProduct {} {displayName, instanceGuid, pathToSignedProductExe, pathToSignedReportingE...

https://riptutorial.com/ja/home 102

Page 122: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

WMI

Get-WmiObject -Class "__Namespace" -Namespace "root"

なをするroot またはのネームスペースのなネームスペースをつけるには、そのネームスペースの__NAMESPACEのオブジェクトをします。

3.0

CIM

> Get-CimInstance -Namespace "root" -ClassName "__Namespace" Name PSComputerName ---- -------------- subscription DEFAULT CIMV2 msdtc Cli SECURITY HyperVCluster SecurityCenter2 RSOP PEH StandardCimv2 WMI directory Policy virtualization Interop Hardware ServiceModel SecurityCenter Microsoft aspnet Appv

WMI

Get-WmiObject -List -Namespace "root"

オンラインでWMIとCIMをむ https://riptutorial.com/ja/powershell/topic/6808/wmiとcim

https://riptutorial.com/ja/home 103

Page 123: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

35: XMLファイルの

Examples

XMLファイルへのアクセス

<!-- file.xml --> <people> <person id="101"> <name>Jon Lajoie</name> <age>22</age> </person> <person id="102"> <name>Lord Gaben</name> <age>65</age> </person> <person id="103"> <name>Gordon Freeman</name> <age>29</age> </person> </people>

XMLファイルのロード

XMLファイルをロードするには、のいずれかをできます。

# First Method $xdoc = New-Object System.Xml.XmlDocument $file = Resolve-Path(".\file.xml") $xdoc.load($file) # Second Method [xml] $xdoc = Get-Content ".\file.xml" # Third Method $xdoc = [xml] (Get-Content ".\file.xml")

オブジェクトとしてのXMLへのアクセス

PS C:\> $xml = [xml](Get-Content file.xml) PS C:\> $xml PS C:\> $xml.people person -------- {Jon Lajoie, Lord Gaben, Gordon Freeman} PS C:\> $xml.people.person id name age

https://riptutorial.com/ja/home 104

Page 124: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

-- ---- --- 101 Jon Lajoie 22 102 Lord Gaben 65 103 Gordon Freeman 29 PS C:\> $xml.people.person[0].name Jon Lajoie PS C:\> $xml.people.person[1].age 65 PS C:\> $xml.people.person[2].id 103

XPathによるXMLへのアクセス

PS C:\> $xml = [xml](Get-Content file.xml) PS C:\> $xml PS C:\> $xml.SelectNodes("//people") person -------- {Jon Lajoie, Lord Gaben, Gordon Freeman} PS C:\> $xml.SelectNodes("//people//person") id name age -- ---- --- 101 Jon Lajoie 22 102 Lord Gaben 65 103 Gordon Freeman 29 PS C:\> $xml.SelectSingleNode("people//person[1]//name") Jon Lajoie PS C:\> $xml.SelectSingleNode("people//person[2]//age") 65 PS C:\> $xml.SelectSingleNode("people//person[3]//@id") 103

XPathでをむXMLにアクセスする

PS C:\> [xml]$xml = @" <ns:people xmlns:ns="http://schemas.xmlsoap.org/soap/envelope/"> <ns:person id="101"> <ns:name>Jon Lajoie</ns:name> </ns:person> <ns:person id="102"> <ns:name>Lord Gaben</ns:name> </ns:person> <ns:person id="103"> <ns:name>Gordon Freeman</ns:name> </ns:person> </ns:people> "@

https://riptutorial.com/ja/home 105

Page 125: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS C:\> $ns = new-object Xml.XmlNamespaceManager $xml.NameTable PS C:\> $ns.AddNamespace("ns", $xml.DocumentElement.NamespaceURI) PS C:\> $xml.SelectNodes("//ns:people/ns:person", $ns) id name -- ---- 101 Jon Lajoie 102 Lord Gaben 103 Gordon Freeman

XmlWriterをしてXMLドキュメントをする

# Set The Formatting $xmlsettings = New-Object System.Xml.XmlWriterSettings $xmlsettings.Indent = $true $xmlsettings.IndentChars = " " # Set the File Name Create The Document $XmlWriter = [System.XML.XmlWriter]::Create("C:\YourXML.xml", $xmlsettings) # Write the XML Decleration and set the XSL $xmlWriter.WriteStartDocument() $xmlWriter.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='style.xsl'") # Start the Root Element $xmlWriter.WriteStartElement("Root") $xmlWriter.WriteStartElement("Object") # <-- Start <Object> $xmlWriter.WriteElementString("Property1","Value 1") $xmlWriter.WriteElementString("Property2","Value 2") $xmlWriter.WriteStartElement("SubObject") # <-- Start <SubObject> $xmlWriter.WriteElementString("Property3","Value 3") $xmlWriter.WriteEndElement() # <-- End <SubObject> $xmlWriter.WriteEndElement() # <-- End <Object> $xmlWriter.WriteEndElement() # <-- End <Root> # End, Finalize and close the XML Document $xmlWriter.WriteEndDocument() $xmlWriter.Flush() $xmlWriter.Close()

XMLファイル

<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type='text/xsl' href='style.xsl'?> <Root> <Object> <Property1>Value 1</Property1> <Property2>Value 2</Property2> <SubObject> <Property3>Value 3</Property3> </SubObject> </Object> </Root>

https://riptutorial.com/ja/home 106

Page 126: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

のXMLDocumentにXMLのスニペットをする

サンプルデータ

XMLドキュメント

まず、のディレクトリに「 books.xml 」というサンプルXMLドキュメントをしましょう。

<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>Of Mice And Men</title> <author>John Steinbeck</author> <pageCount>187</pageCount> <publishers> <publisher> <isbn>978-88-58702-15-4</isbn> <name>Pascal Covici</name> <year>1937</year> <binding>Hardcover</binding> <first>true</first> </publisher> <publisher> <isbn>978-05-82461-46-8</isbn> <name>Longman</name> <year>2009</year> <binding>Hardcover</binding> </publisher> </publishers> <characters> <character name="Lennie Small" /> <character name="Curley's Wife" /> <character name="George Milton" /> <character name="Curley" /> </characters> <film>True</film> </book> <book> <title>The Hunt for Red October</title> <author>Tom Clancy</author> <pageCount>387</pageCount> <publishers> <publisher> <isbn>978-08-70212-85-7</isbn> <name>Naval Institute Press</name> <year>1984</year> <binding>Hardcover</binding> <first>true</first> </publisher> <publisher> <isbn>978-04-25083-83-3</isbn> <name>Berkley</name> <year>1986</year> <binding>Paperback</binding> </publisher> <publisher>

https://riptutorial.com/ja/home 107

Page 127: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

<isbn>978-08-08587-35-4</isbn> <name>Penguin Putnam</name> <year>2010</year> <binding>Paperback</binding> </publisher> </publishers> <characters> <character name="Marko Alexadrovich Ramius" /> <character name="Jack Ryan" /> <character name="Admiral Greer" /> <character name="Bart Mancuso" /> <character name="Vasily Borodin" /> </characters> <film>True</film> </book> </books>

しいデータ

たちがしたいことは、このにいくつかのしいをすることです。Tom ClancyのPatriot Games はい、はClancyののファンです^^とSci-Fiのおにり Hitchhiker's Galaxy Douglas Adamsのなは、Zaphod Beeblebroxがむのがしいからです。

とかしいのデータをし、PSCustomObjectsのリストとしてしました。

$newBooks = @( [PSCustomObject] @{ "Title" = "Patriot Games"; "Author" = "Tom Clancy"; "PageCount" = 540; "Publishers" = @( [PSCustomObject] @{ "ISBN" = "978-0-39-913241-4"; "Year" = "1987"; "First" = $True; "Name" = "Putnam"; "Binding" = "Hardcover"; } ); "Characters" = @( "Jack Ryan", "Prince of Wales", "Princess of Wales", "Robby Jackson", "Cathy Ryan", "Sean Patrick Miller" ); "film" = $True; }, [PSCustomObject] @{ "Title" = "The Hitchhiker's Guide to the Galaxy"; "Author" = "Douglas Adams"; "PageCount" = 216; "Publishers" = @( [PSCustomObject] @{ "ISBN" = "978-0-33-025864-7"; "Year" = "1979"; "First" = $True; "Name" = "Pan Books"; "Binding" = "Hardcover"; }

https://riptutorial.com/ja/home 108

Page 128: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

); "Characters" = @( "Arthur Dent", "Marvin", "Zaphod Beeblebrox", "Ford Prefect", "Trillian", "Slartibartfast", "Dirk Gently" ); "film" = $True; } );

テンプレート

しいデータをれるために、いくつかのスケルトンXMLをするがあります。には、データのリストにしてスケルトン/テンプレートをするがあります。このでは、ブック、、パブリッシャーのテンプレートがです。これをして、 filmタグのなど、いくつかのデフォルトをすることもできます。

$t_book = [xml] @' <book> <title /> <author /> <pageCount /> <publishers /> <characters /> <film>False</film> </book> '@; $t_publisher = [xml] @' <publisher> <isbn/> <name/> <year/> <binding/> <first>false</first> </publisher> '@; $t_character = [xml] @' <character name="" /> '@;

たちはセットアップをえました。

しいデータをするは、サンプルデータをすべてセットアップしたので、カスタムオブジェクトをXMLドキュメントオブジェクトにしましょう。

# Read the xml document $xml = [xml] Get-Content .\books.xml; # Let's show a list of titles to see what we've got currently:

https://riptutorial.com/ja/home 109

Page 129: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$xml.books.book | Select Title, Author, @{N="ISBN";E={If ( $_.Publishers.Publisher.Count ) { $_.Publishers.publisher[0].ISBN} Else { $_.Publishers.publisher.isbn}}};; # Outputs: # title author ISBN # ----- ------ ---- # Of Mice And Men John Steinbeck 978-88-58702-15-4 # The Hunt for Red October Tom Clancy 978-08-70212-85-7 # Let's show our new books as well: $newBooks | Select Title, Author, @{N="ISBN";E={$_.Publishers[0].ISBN}}; # Outputs: # Title Author ISBN # ----- ------ ---- # Patriot Games Tom Clancy 978-0-39-913241-4 # The Hitchhiker's Guide to the Galaxy Douglas Adams 978-0-33-025864-7 # Now to merge the two: ForEach ( $book in $newBooks ) { $root = $xml.SelectSingleNode("/books"); # Add the template for a book as a new node to the root element [void]$root.AppendChild($xml.ImportNode($t_book.book, $true)); # Select the new child element $newElement = $root.SelectSingleNode("book[last()]"); # Update the parameters of that new element to match our current new book data $newElement.title = [String]$book.Title; $newElement.author = [String]$book.Author; $newElement.pageCount = [String]$book.PageCount; $newElement.film = [String]$book.Film; # Iterate through the properties that are Children of our new Element: ForEach ( $publisher in $book.Publishers ) { # Create the new child publisher element # Note the use of "SelectSingleNode" here, this allows the use of the "AppendChild" method as it returns # a XmlElement type object instead of the $Null data that is currently stored in that leaf of the # XML document tree [void]$newElement.SelectSingleNode("publishers").AppendChild($xml.ImportNode($t_publisher.publisher,$true)); # Update the attribute and text values of our new XML Element to match our new data $newPublisherElement = $newElement.SelectSingleNode("publishers/publisher[last()]"); $newPublisherElement.year = [String]$publisher.Year; $newPublisherElement.name = [String]$publisher.Name; $newPublisherElement.binding = [String]$publisher.Binding; $newPublisherElement.isbn = [String]$publisher.ISBN; If ( $publisher.first ) { $newPublisherElement.first = "True"; } } ForEach ( $character in $book.Characters ) { # Select the characters xml element $charactersElement = $newElement.SelectSingleNode("characters");

https://riptutorial.com/ja/home 110

Page 130: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# Add a new character child element [void]$charactersElement.AppendChild($xml.ImportNode($t_character.character, $true)); # Select the new characters/character element $characterElement = $charactersElement.SelectSingleNode("character[last()]"); # Update the attribute and text values to match our new data $characterElement.name = [String]$character; } } # Check out the new XML: $xml.books.book | Select Title, Author, @{N="ISBN";E={If ( $_.Publishers.Publisher.Count ) { $_.Publishers.publisher[0].ISBN} Else { $_.Publishers.publisher.isbn}}}; # Outputs: # title author ISBN # ----- ------ ---- # Of Mice And Men John Steinbeck 978-88-58702-15-4 # The Hunt for Red October Tom Clancy 978-08-70212-85-7 # Patriot Games Tom Clancy 978-0-39-913241-4 # The Hitchhiker's Guide to the Galaxy Douglas Adams 978-0-33-025864-7

XMLをディスク、スクリーン、ウェブ、またはどこにでもくことができるようになりました

これはのためのきではないかもしれませんが、 [void]$xml.SelectSingleNode("/complicated/xpath/goes[here]").AppendChild($xml.CreateElement("newElementName")

をけるためにそれをつけました[void]$xml.SelectSingleNode("/complicated/xpath/goes[here]").AppendChild($xml.CreateElement("newElementName") $xml.SelectSingleNode("/complicated/xpath/goes/here/newElementName") = $textValue

は、このでされているメソッドは、よりされており、ののためにするのがだといます。

のテンプレートとしてセクションをするのではなく、をつをむようにテンプレートをすることができます。あなたは、リストをループするときにのをするようにをらなければなりません。

オンラインでXMLファイルのをむ https://riptutorial.com/ja/powershell/topic/4882/xmlファイルの

https://riptutorial.com/ja/home 111

Page 131: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

36: アーカイブモジュール

アーカイブモジュールMicrosoft.PowerShell.Archiveは、ファイルをZIPアーカイブ Compress-

Archive にし、 Expand-Archive するためのをします。このモジュールは、PowerShell 5.0でできます。

のバージョンのPowerShellでは、 Community Extensionsまたは.NET

System.IO.Compression.FileSystemをできました。

Expand-Archive / Compress-Archive•-パス

するファイルCompress-ArchiveのパスまたはファイルのをするためのアーカイブのパスExpand-Archive

そののパスのオプションがいくつかあります。をごください。○

-DestinationPath オプションこのパスをしないと、のディレクトリCompress-Archiveにアーカイブがされるか、アーカイブのがのディレクトリExpand-Archiveにされます。

パラメーター

パラメータ

CompressionLevelアーカイブのみレベルをFastest 、 OptimalまたはNoCompressionのいずれかにします

のをめるプロンプト

せずにコマンドをさせます。

LiteralPathりされるパス、 ワイルドカードがサポートされないパス,のパスをするパス

パス し、ワイルドカードをめることができますパスは,のパスをするには

Compress-Archiveのみのアーカイブをする

に コマンドをシミュレートする

については、 MSDN Microsoft.PowerShell.Archive5.1をしてください。

https://riptutorial.com/ja/home 112

Page 132: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Examples

ワイルドカードによるアーカイブ

Compress-Archive -Path C:\Documents\* -CompressionLevel Optimal -DestinationPath C:\Archives\Documents.zip

このコマンドはのとおりです。

C:\Documentsのすべてのファイルをする•Optimalを•のアーカイブをC:\Archives\Documents.zipします。

-DestinationPathは、しないは.zipをします。○

-LiteralPathは、 .zipけずにをけるがあるにできます。○

のZIPをCompress-Archiveでする

Compress-Archive -Path C:\Documents\* -Update -DestinationPath C:\Archives\Documents.zip

これは、すべてのファイルDocuments.zipをC:\Documentsしいファイルでまたはきえます•

Expand-Archiveでをする

Expand-Archive -Path C:\Archives\Documents.zip -DestinationPath C:\Documents

Documents.zipからすべてのファイルをC:\DocumentsフォルダにしますC:\Documents•

オンラインでアーカイブモジュールをむ https://riptutorial.com/ja/powershell/topic/9896/アーカイブモジュール

https://riptutorial.com/ja/home 113

Page 133: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

37: インフラストラクチャの

インフラストラクチャサービスをすることで、のツール、オーケストレータ、オーケストレーションエンジン、スクリプト、およびなUIをして、FTEをするだけでなく、にれたROIをることができます

Examples

コンソールアプリケーションのブラックボックステストのなスクリプト

これは、ととするコンソールアプリケーションのテストをするのなです。

テストされたアプリケーションは、しいをみんでし、1つのいがされたにをします。パワーシェルスクリプトは、がすると "pass"をきみます。

$process = New-Object System.Diagnostics.Process $process.StartInfo.FileName = ".\ConsoleApp1.exe" $process.StartInfo.UseShellExecute = $false $process.StartInfo.RedirectStandardOutput = $true $process.StartInfo.RedirectStandardInput = $true if ( $process.Start() ) { # input $process.StandardInput.WriteLine("1"); $process.StandardInput.WriteLine("2"); $process.StandardInput.WriteLine("3"); $process.StandardInput.WriteLine(); $process.StandardInput.WriteLine(); # output check $output = $process.StandardOutput.ReadToEnd() if ( $output ) { if ( $output.Contains("sum 6") ) { Write "pass" } else { Write-Error $output } } $process.WaitForExit() }

オンラインでインフラストラクチャのをむ https://riptutorial.com/ja/powershell/topic/10909/インフラストラクチャの

https://riptutorial.com/ja/home 114

Page 134: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

38: エイリアスPowershellのシステムには、コマンドレットのけにするながありますについては、[トピックがされていません]を。しかし、インタラクティブにディレクトリにファイルをリストするたびに、 Get-ChildItemsをするのはにではありません。 したがって、Powershellでは、コマンドレットのわりにショートカット - エイリアスをできます。

Get-ChildItemわりにls 、 dirまたはgci 、じをることがGet-ChildItem 。エイリアスは、そのコマンドレットとです。

なエイリアスのはのとおりです。

エイリアス コマンドレット

、foreach For EachObject

、どこで - オブジェクト

cat、gc、type Get-Content

cd、chdir、sl セット・ロケーション

CLS、クリア クリアホスト

cp、copy、cpi コピーアイテム

ディレクトリ/ ls / gci Get-ChildItem

エコー、きみ きみ

fl フォーマットリスト

フィート フォーマットテーブル

fw フォーマットワイド

gc、pwd

gm Get-Member

iex びし

ii Invoke-Item

mv、

https://riptutorial.com/ja/home 115

Page 135: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

エイリアス コマンドレット

rm、rmdir、del、erase、rd、ri アイテムを

スタート - スリープ

める、る プロセス

のでは、エイリアスがどのようにのcmd、bashからられているコマンドのシミュレーションをにしたかをることができます。

Examples

Get-Alias

すべてのエイリアスとそのをするには

Get-Alias

のコマンドレットのエイリアスをすべてするには

PS C:\> get-alias -Definition Get-ChildItem CommandType Name Version Source ----------- ---- ------- ------ Alias dir -> Get-ChildItem Alias gci -> Get-ChildItem Alias ls -> Get-ChildItem

するエイリアスをつけるには

PS C:\> get-alias -Name p* CommandType Name Version Source ----------- ---- ------- ------ Alias popd -> Pop-Location Alias proc -> Get-Process Alias ps -> Get-Process Alias pushd -> Push-Location Alias pwd -> Get-Location

セットエイリアス

このコマンドレットをすると、のコマンドレットのしいをできます

PS C:\> Set-Alias -Name proc -Value Get-Process PS C:\> proc Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id SI ProcessName ------- ------ ----- ----- ----- ------ -- -- -----------

https://riptutorial.com/ja/home 116

Page 136: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

292 17 13052 20444 ...19 7.94 620 1 ApplicationFrameHost ....

するエイリアスはのセッションでのみされることにしてください。しいセッションをするときに、エイリアスをするがあります。 Powershellプロファイル[まだされていないトピック]をは、これらのにです。

オンラインでエイリアスをむ https://riptutorial.com/ja/powershell/topic/5287/エイリアス

https://riptutorial.com/ja/home 117

Page 137: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

39: エラー

このトピックでは、PowerShellのエラータイプとエラーについてします。

Examples

エラーの

エラーはエラーです。そのにどのようながあるのだろうかとにうかもしれません。まあ、powershellでは、このエラーはきく2つのにされます。

エラー•しないエラー•

がすように、エラーはをさせ、エラーはをのステートメントにさせます。

$ ErrorActionPreferenceのがデフォルトContinueであるとすると、これはです。 $ ErrorActionPreferenceは、 ""エラーののをpowershellにするPrefrenceです。

エラー

エラーは、のようになtry catchでできます

Try { Write-Host "Attempting Divide By Zero" 1/0 } Catch { Write-Host "A Terminating Error: Divide by Zero Caught!" }

のスニペットがされ、catchブロックをしてエラーがされます。

エラー

、エラーは、デフォルトでcatchブロックにされません。そのは、Non-Terminatingエラーはなエラーとはみなされないからです。

Try { Stop-Process -Id 123456 } Catch

https://riptutorial.com/ja/home 118

Page 138: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

{ Write-Host "Non-Terminating Error: Invalid Process ID" }

のをすると、catchブロックからのはられません。なぜなら、エラーはではないとみなされ、はにのコマンドからするからです。ただし、コンソールにエラーがされます。しないエラーをするには、エラーのをにするがあります。

Try { Stop-Process -Id 123456 -ErrorAction Stop } Catch { "Non-Terminating Error: Invalid Process ID" }

さて、されたエラーでは、このエラーはエラーとみなされ、catchブロックでされます。

およびしていないエラーのびし

Write-Errorコマンドレットは、にびすホストプログラムにエラーをきみます。それはをしません。どこからスローするとエラーがし、をします

Write-host "Going to try a non terminating Error " Write-Error "Non terminating" Write-host "Going to try a terminating Error " throw "Terminating Error " Write-host "This Line wont be displayed"

オンラインでエラーをむ https://riptutorial.com/ja/powershell/topic/8075/エラー

https://riptutorial.com/ja/home 119

Page 139: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

40: オブジェクトの

Examples

オブジェクトの

プロパティののオブジェクトにプロパティをするは、Add-Memberコマンドレットをできます。 PSObjectsでは、は「ノートプロパティ」のタイプでされます。

$object = New-Object -TypeName PSObject -Property @{ Name = $env:username ID = 12 Address = $null } Add-Member -InputObject $object -Name "SomeNewProp" -Value "A value" -MemberType NoteProperty # Returns PS> $Object Name ID Address SomeNewProp ---- -- ------- ----------- nem 12 A value

Select-Objectコマンドレットいわゆるされたプロパティでプロパティをすることもできます。

$newObject = $Object | Select-Object *, @{label='SomeOtherProp'; expression={'Another value'}} # Returns PS> $newObject Name ID Address SomeNewProp SomeOtherProp ---- -- ------- ----------- ------------- nem 12 A value Another value

のコマンドはのようにできます

$newObject = $Object | Select *,@{l='SomeOtherProp';e={'Another value'}}

プロパティのSelect-Objectコマンドレットをして、オブジェクトからプロパティをできます。

$object = $newObject | Select-Object * -ExcludeProperty ID, Address # Returns

https://riptutorial.com/ja/home 120

Page 140: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS> $object Name SomeNewProp SomeOtherProp ---- ----------- ------------- nem A value Another value

しいオブジェクトをする

PowerShellは、のスクリプトとはなり、オブジェクトをパイプラインでします。つまり、あるコマンドからのコマンドにデータをする、オブジェクトの、、およびがです。

オブジェクトのはです。するほとんどのオブジェクトはPowerShellのカスタムオブジェクトになり、そのオブジェクトにするはPSObjectです。 PowerShellでは、.NETでできるオブジェクトをすることもできます。

に、いくつかのプロパティをつしいオブジェクトをするをします。

オプション1オブジェクト$newObject = New-Object -TypeName PSObject -Property @{ Name = $env:username ID = 12 Address = $null } # Returns PS> $newObject Name ID Address ---- -- ------- nem 12

にオブジェクトをするには、コマンドのに$newObject =

また、オブジェクトのコレクションをするがあります。これは、のコレクションをし、コレクションにオブジェクトをすることによってうことができます。

$newCollection = @() $newCollection += New-Object -TypeName PSObject -Property @{ Name = $env:username ID = 12 Address = $null }

このコレクションオブジェクトをオブジェクトごとにすることができます。これをうには、ドキュメントの「Loop」セクションをします。

オプション2Select-Object

https://riptutorial.com/ja/home 121

Page 141: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

あまりでないでインターネットでつかるオブジェクトをするはのとおりです。

$newObject = 'unuseddummy' | Select-Object -Property Name, ID, Address $newObject.Name = $env:username $newObject.ID = 12 # Returns PS> $newObject Name ID Address ---- -- ------- nem 12

オプション3pscustomobjectタイプアクセラレータPSv3 +

けされたのアクセラレータは、PowerShellがしたでプロパティをするようにします。 [PSCustomObject]をするために、きアクセラレータはありません。

$newObject = [PSCustomObject][Ordered]@{ Name = $env:Username ID = 12 Address = $null } # Returns PS> $newObject Name ID Address ---- -- ------- nem 12

オブジェクトをべる

オブジェクトがあるので、それがであるかするといかもしれません。 Get-Memberコマンドレットをして、オブジェクトのとオブジェクトのをできます。

Get-Item c:\windows | Get-Member

これにより、

TypeName: System.IO.DirectoryInfo

オブジェクトにはプロパティとメソッドのリストがきます。

オブジェクトのをするのは、のようにGetTypeメソッドをすることです。

C:\> $Object = Get-Item C:\Windows C:\> $Object.GetType()

https://riptutorial.com/ja/home 122

Page 142: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True DirectoryInfo System.IO.FileSystemInfo

オブジェクトがつプロパティのリストをするには、そのとともにFormat-Listコマンドレットをして、プロパティパラメータに*すべてをするをします。

はのようになります。

C:\> Get-Item C:\Windows | Format-List -Property * PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Windows PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\ PSChildName : Windows PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : True Mode : d----- BaseName : Windows Target : {} LinkType : Name : Windows Parent : Exists : True Root : C:\ FullName : C:\Windows Extension : CreationTime : 30/10/2015 06:28:30 CreationTimeUtc : 30/10/2015 06:28:30 LastAccessTime : 16/08/2016 17:32:04 LastAccessTimeUtc : 16/08/2016 16:32:04 LastWriteTime : 16/08/2016 17:32:04 LastWriteTimeUtc : 16/08/2016 16:32:04 Attributes : Directory

クラスのインスタンスの

PowerShell 5.1でかれたGeneric Classesのインスタンスをすることができます

#Nullable System.DateTime [Nullable[datetime]]$nullableDate = Get-Date -Year 2012 $nullableDate $nullableDate.GetType().FullName $nullableDate = $null $nullableDate #Normal System.DateTime [datetime]$aDate = Get-Date -Year 2013 $aDate $aDate.GetType().FullName $aDate = $null #Throws exception when PowerShell attempts to convert null to

をえる

https://riptutorial.com/ja/home 123

Page 143: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Saturday, 4 August 2012 08:53:02 System.DateTime Sunday, 4 August 2013 08:53:02 System.DateTime Cannot convert null to type "System.DateTime". At line:14 char:1 + $aDate = $null + ~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException

なコレクションもです

[System.Collections.Generic.SortedDictionary[int, String]]$dict = [System.Collections.Generic.SortedDictionary[int, String]]::new() $dict.GetType().FullName $dict.Add(1, 'a') $dict.Add(2, 'b') $dict.Add(3, 'c') $dict.Add('4', 'd') #powershell auto converts '4' to 4 $dict.Add('5.1', 'c') #powershell auto converts '5.1' to 5 $dict $dict.Add('z', 'z') #powershell can't convert 'z' to System.Int32 so it throws an error

をえる

System.Collections.Generic.SortedDictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] Key Value --- ----- 1 a 2 b 3 c 4 d 5 c Cannot convert argument "key", with value: "z", for "Add" to type "System.Int32": "Cannot convert value "z" to type "System.Int32". Error: "Input string was not in a correct format."" At line:15 char:1 + $dict.Add('z', 'z') #powershell can't convert 'z' to System.Int32 so ... + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

オンラインでオブジェクトのをむ https://riptutorial.com/ja/powershell/topic/1328/オブジェクトの

https://riptutorial.com/ja/home 124

Page 144: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

41: コマンドレットのけ

をめるために、 <verb>-<noun>をしてCmdLetをするがあります。

Examples

CmdLetsのをけるは、 Get-Verb

ののは、Windows PowerShellのみ

はにであるべきです。

としてください。たとえば、 Find-Packageにはプロバイダがです。そのは、 ProviderPackageではなくPackageProviderです。

オンラインでコマンドレットのけをむ https://riptutorial.com/ja/powershell/topic/8703/コマンドレットのけ

https://riptutorial.com/ja/home 125

Page 145: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

42: コメントベースのヘルプ

PowerShellには、コメントベースのヘルプとばれるドキュメントメカニズムがあります。コードコメントきのスクリプトやをすることができます。コメントベースのヘルプは、くの、のヘルプキーワードをむコメントブロックでかれています。ヘルプキーワードはドットでまり、 Get-Helpコマンドレットをするとされるヘルプセクションをします。

Examples

のコメントベースのヘルプ

<# .SYNOPSIS Gets the content of an INI file. .DESCRIPTION Gets the content of an INI file and returns it as a hashtable. .INPUTS System.String .OUTPUTS System.Collections.Hashtable .PARAMETER FilePath Specifies the path to the input INI file. .EXAMPLE C:\PS>$IniContent = Get-IniContent -FilePath file.ini C:\PS>$IniContent['Section1'].Key1 Gets the content of file.ini and access Key1 from Section1. .LINK Out-IniFile #> function Get-IniContent { [CmdletBinding()] Param ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [ValidateScript({(Test-Path $_) -and ((Get-Item $_).Extension -eq ".ini")})] [System.String]$FilePath ) # Initialize output hash table. $ini = @{} switch -regex -file $FilePath

https://riptutorial.com/ja/home 126

Page 146: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

{ "^\[(.+)\]$" # Section { $section = $matches[1] $ini[$section] = @{} $CommentCount = 0 } "^(;.*)$" # Comment { if( !($section) ) { $section = "No-Section" $ini[$section] = @{} } $value = $matches[1] $CommentCount = $CommentCount + 1 $name = "Comment" + $CommentCount $ini[$section][$name] = $value } "(.+?)\s*=\s*(.*)" # Key { if( !($section) ) { $section = "No-Section" $ini[$section] = @{} } $name,$value = $matches[1..2] $ini[$section][$name] = $value } } return $ini }

Get-Help -Name Get-IniContent -Fullすると、のドキュメントがされます。

https://riptutorial.com/ja/home 127

Page 147: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

aでまるコメントにづいたキーワードにしてください. Get-Helpセクションにします。

スクリプトコメントベースのヘルプ

<# .SYNOPSIS Reads a CSV file and filters it.

https://riptutorial.com/ja/home 128

Page 148: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

.DESCRIPTION The ReadUsersCsv.ps1 script reads a CSV file and filters it on the 'UserName' column. .PARAMETER Path Specifies the path of the CSV input file. .INPUTS None. You cannot pipe objects to ReadUsersCsv.ps1. .OUTPUTS None. ReadUsersCsv.ps1 does not generate any output. .EXAMPLE C:\PS> .\ReadUsersCsv.ps1 -Path C:\Temp\Users.csv -UserName j.doe #> Param ( [Parameter(Mandatory=$true,ValueFromPipeline=$false)] [System.String] $Path, [Parameter(Mandatory=$true,ValueFromPipeline=$false)] [System.String] $UserName ) Import-Csv -Path $Path | Where-Object -FilterScript {$_.UserName -eq $UserName}

のスクリプトドキュメントは、 Get-Help -Name ReadUsersCsv.ps1 -Fullするとできます。

https://riptutorial.com/ja/home 129

Page 150: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

43: スイッチ

switchをすると、のリストとのをテストできます。はケースとばれ、 スイッチオンされているはスイッチのケースごとにチェックされます。のオプションからできるスクリプトをくことができますが、いのifをくはありません。

このトピックでは、スクリプトのフローをするためにされるswitchについてします。ブーリアンフラグとしてでされるスイッチパラメータとしないでください。

Examples

シンプルなスイッチ

switchは、のテストをのとし、したのためにするアクションをします。のマッチ/アクションがするがあります。

えられたのスイッチ...

switch($myValue) { 'First Condition' { 'First Action' } 'Second Condition' { 'Second Action' } }

$myValueが'First Condition'されている、 'First Action'がされます。

$myValueが'Second Condition'されている、 'Section Action'がされます。

$myValueがどちらのともしない、もされません。

Regexパラメータをしたswitch

-Regexパラメータをすると、switchがにしてマッチングをできます。

switch -Regex ('Condition') { 'Con\D+ion' {'One or more non-digits'} 'Conditio*$' {'Zero or more "o"'} 'C.ndition' {'Any single char.'} '^C\w+ition$' {'Anchors and one or more word chars.'} 'Test' {'No match'} }

One or more non-digits

https://riptutorial.com/ja/home 131

Page 151: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Any single char. Anchors and one or more word chars.

きのなスイッチ

switchでbreakキーワードをすると、すべてのをするにをできます。

switch('Condition') { 'Condition' { 'First Action' } 'Condition' { 'Second Action' break } 'Condition' { 'Third Action' } }

First Action Second Action

2のアクションでbreakキーワードがあるため、3のはされません。

ワイルドカードパラメータをしたswitch

-Wildcardパラメータをすると、switchはにしてワイルドカードマッチングをできます。

switch -Wildcard ('Condition') { 'Condition' {'Normal match'} 'Condit*' {'Zero or more wildcard chars.'} 'C[aoc]ndit[f-l]on' {'Range and set of chars.'} 'C?ndition' {'Single char. wildcard'} 'Test*' {'No match'} }

Normal match Zero or more wildcard chars. Range and set of chars. Single char. wildcard

なパラメータをつswitch

-Exactパラメータは、switch-statementがstring-conditionsにしてとをしないをするように-Exactます。

https://riptutorial.com/ja/home 132

Page 152: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

switch -Exact ('Condition') { 'condition' {'First Action'} 'Condition' {'Second Action'} 'conditioN' {'Third Action'} '^*ondition$' {'Fourth Action'} 'Conditio*' {'Fifth Action'} }

First Action Second Action Third Action

するがとしているため、1から3のアクションがされます。 4と5ののとワイルドカードはしません。

マッチングがされている、とする4のもありますが、このはされます。

CaseSensitiveパラメータをしたSwitchステートメント

-CaseSensitiveパラメータは、switchをして、にしてとをにさせます。

switch -CaseSensitive ('Condition') { 'condition' {'First Action'} 'Condition' {'Second Action'} 'conditioN' {'Third Action'} }

Second Action

2のアクションは、とのをしたときに'Condition'というとにするのであるため、されるのアクションです。

ファイルパラメータをしたswitch

-fileパラメータをすると、switchはファイルからをけることができます。ファイルのはswitchによってされます。

サンプルファイルinput.txt

condition test

switchの

switch -file input.txt { 'condition' {'First Action'} 'test' {'Second Action'}

https://riptutorial.com/ja/home 133

Page 153: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

'fail' {'Third Action'} }

First Action Second Action

デフォルトののシンプルなスイッチ

Defaultキーワードは、のがとしないにアクションをするためにされます。

switch('Condition') { 'Skip Condition' { 'First Action' } 'Skip This Condition Too' { 'Second Action' } Default { 'Default Action' } }

Default Action

をしたステートメントのりえ

はでもあります。

$myInput = 0 switch($myInput) { # because the result of the expression, 4, # does not equal our input this block should not be run. (2+2) { 'True. 2 +2 = 4' } # because the result of the expression, 0, # does equal our input this block should be run. (2-2) { 'True. 2-2 = 0' } # because our input is greater than -1 and is less than 1 # the expression evaluates to true and the block should be run. { $_ -gt -1 -and $_ -lt 1 } { 'True. Value is 0' } } #Output True. 2-2 = 0 True. Value is 0

オンラインでスイッチをむ https://riptutorial.com/ja/powershell/topic/1174/スイッチ

https://riptutorial.com/ja/home 134

Page 154: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

44: スクリプトのの#Requires -Version <N> [。<n>]•

#Requires -PSSnapin <PSSnapin-Name> [-Version <N> [。<n>]]•#Requires -Modules {<Module-Name> | <Hashtable>}•#Requires -ShellId <ShellId>•#Requires -RunAsAdministrator•

#requiresステートメントは、スクリプトののにくことができますのであるはありませんが、そのののステートメントでなければなりません。

1つのスクリプトでの#requiresをできます。

については、Technet - about_about_Requiresのをしてください。

Examples

PowerShellホストのバージョンをする

#requires -version 4

のバージョンでこのスクリプトをしようとすると、このエラーメッセージがされます

。\ script.ps1スクリプト 'script.ps1'は、Windows PowerShellバージョン5.0の1に「#requires」ステートメントがまれているため、できません。スクリプトでなバージョンが、のバージョンのWindows PowerShellバージョン2.0としません。

admininstratorとしてスクリプトをする

4.0

#requires -RunAsAdministrator

なしでこのスクリプトをしようとすると、このエラーメッセージがされます

。\ script.ps1スクリプト 'script.ps1'は、としてするための「#requires」ステートメントがまれているため、できません。のWindows PowerShellセッションはとしてされていません。 [として]オプションをしてWindows PowerShellをし、スクリプトをしてみます。

オンラインでスクリプトののをむ https://riptutorial.com/ja/powershell/topic/5637/スクリプトのの

https://riptutorial.com/ja/home 135

Page 155: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

45: スケジュールされたタスクモジュール

Windows 8 / Server 2012でなScheduled Tasksモジュールのの。

Examples

スケジュールされたタスクでPowerShellスクリプトをする

すぐにされるスケジュールされたタスクをし、にC:\myscript.ps1をSYSTEMとしてする

$ScheduledTaskPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount $ScheduledTaskTrigger1 = New-ScheduledTaskTrigger -AtStartup $ScheduledTaskTrigger2 = New-ScheduledTaskTrigger -Once -At $(Get-Date) -RepetitionInterval "00:01:00" -RepetitionDuration $([timeSpan] "24855.03:14:07") $ScheduledTaskActionParams = @{ Execute = "PowerShell.exe" Argument = '-executionpolicy Bypass -NonInteractive -c C:\myscript.ps1 -verbose >> C:\output.log 2>&1"' } $ScheduledTaskAction = New-ScheduledTaskAction @ScheduledTaskActionParams Register-ScheduledTask -Principal $ScheduledTaskPrincipal -Trigger @($ScheduledTaskTrigger1,$ScheduledTaskTrigger2) -TaskName "Example Task" -Action $ScheduledTaskAction

オンラインでスケジュールされたタスクモジュールをむ

https://riptutorial.com/ja/powershell/topic/10940/スケジュールされたタスクモジュール

https://riptutorial.com/ja/home 136

Page 156: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

46: スプラット

スプラッティングは、のパラメータを1つのユニットとしてコマンドにすです。これは、パラメータとそのをハッシュテーブルにキーとのペアとしてし、スプラット@をしてコマンドレットにスプラットすることによってわれます。

スプラッティングは、コマンドをよりみやすくし、のコマンドびしでパラメータをできるようにします。

または@()は、Splatting@はまったくなるをします。

about_Splatting @ TechNetでをむ

Examples

スプラットパラメータ

スプラットは、コマンド・コールでパラメータとのHashTableをむをするときに$$をスプラット@にきえることによってわれます。

$MyParameters = @{ Name = "iexplore" FileVersionInfo = $true } Get-Process @MyParameters

スプラットなし

Get-Process -Name "iexplore" -FileVersionInfo

のパラメータとスプラットされたパラメータをみわせて、びしにのパラメータをにすることができます。

$MyParameters = @{ ComputerName = "StackOverflow-PC" } Get-Process -Name "iexplore" @MyParameters Invoke-Command -ScriptBlock { "Something to excute remotely" } @MyParameters

Splattingをしたスイッチパラメータのけし

https://riptutorial.com/ja/home 137

Page 157: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Splattingをして、 -FileVersionInfoような-FileVersionInfoスイッチでGet-Processをびすには

Get-Process -FileVersionInfo

これはスプラットをしたびしです。

$MyParameters = @{ FileVersionInfo = $true } Get-Process @MyParameters

これはなのは、デフォルトのパラメタのセットをし、このようなもびしをうことができるからです

$MyParameters = @{ FileVersionInfo = $true } Get-Process @MyParameters -Name WmiPrvSE Get-Process @MyParameters -Name explorer

とスプラット

スプラットのは、パラメータのセットを、またはわずかなバリエーションでするにです。

$splat = @{ Class = "Win32_SystemEnclosure" Property = "Manufacturer" ErrorAction = "Stop" } Get-WmiObject -ComputerName $env:COMPUTERNAME @splat Get-WmiObject -ComputerName "Computer2" @splat Get-WmiObject -ComputerName "Computer3" @splat

ただし、スプラットがのためにインデントされていないは、したくないがあります。わりにパイプすることができます

@{ ComputerName = $env:COMPUTERNAME Class = "Win32_SystemEnclosure" Property = "Manufacturer" ErrorAction = "Stop" } | % { Get-WmiObject @_ }

トップレベルからのへの

スプラットなしでは、コールスタックをしてをしてすのはにです。しかし、 スプラットを@PSBoundParametersのパワーとみわせると、トップレベルのパラメータコレクションをレイヤ

https://riptutorial.com/ja/home 138

Page 158: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

ーにすことができます。

Function Outer-Method { Param ( [string] $First, [string] $Second ) Write-Host ($First) -NoNewline Inner-Method @PSBoundParameters } Function Inner-Method { Param ( [string] $Second ) Write-Host (" {0}!" -f $Second) } $parameters = @{ First = "Hello" Second = "World" } Outer-Method @parameters

オンラインでスプラットをむ https://riptutorial.com/ja/powershell/topic/5647/スプラット

https://riptutorial.com/ja/home 139

Page 159: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

47: スペシャルオペレーター

Examples

をとしてします。

@(Get-ChildItem $env:windir\System32\ntdll.dll)

1つのをむをします

@(Get-ChildItem $env:windir\System32)

フォルダーのすべてのをむをしますこれはからののではありません。

コール

$command = 'Get-ChildItem' & $Command

Get-ChildItemしGet-ChildItem

ドットソーシング

。 。\ myScript.ps1

のスコープの.\myScript.ps1し、のスコープでなとをします。

オンラインでスペシャルオペレーターをむ https://riptutorial.com/ja/powershell/topic/8981/スペシャルオペレーター

https://riptutorial.com/ja/home 140

Page 160: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

48: セキュリティと

Examples

.Netをしてのハッシュコードをする

.Net System.Security.Cryptography.HashAlgorithmをして、サポートされているアルゴリズムをしてメッセージハッシュコードをします。

$example="Nobody expects the Spanish Inquisition." #calculate $hash=[System.Security.Cryptography.HashAlgorithm]::Create("sha256").ComputeHash( [System.Text.Encoding]::UTF8.GetBytes($example)) #convert to hex [System.BitConverter]::ToString($hash) #2E-DF-DA-DA-56-52-5B-12-90-FF-16-FB-17-44-CF-B4-82-DD-29-14-FF-BC-B6-49-79-0C-0E-58-9E-46-2D-3D

"sha256"はされたハッシュアルゴリズムでした。

-するかにする

#convert to lower case hex without '-' [System.BitConverter]::ToString($hash).Replace("-","").ToLower() #2edfdada56525b1290ff16fb1744cfb482dd2914ffbcb649790c0e589e462d3d

base64がされた、にbase64コンバータをする

#convert to base64 [Convert]::ToBase64String($hash) #Lt/a2lZSWxKQ/xb7F0TPtILdKRT/vLZJeQwOWJ5GLT0=

オンラインでセキュリティとをむ https://riptutorial.com/ja/powershell/topic/5683/セキュリティと

https://riptutorial.com/ja/home 141

Page 161: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

49: パッケージ

PowerShellパッケージをすると、PowerShellモジュールおよびそののパッケージを、インストール、、アンインストールできます。

PowerShellGallery.comは、PowerShellモジュールのデフォルトのソースです。なパッケージをサイトでして、コードをコマンドしてプレビューすることもできます。

Examples

パターンをしてPowerShellモジュールをする

DSCでわるモジュールをつけるには

Find-Module -Name *DSC

のPowerShellモジュールリポジトリをする

なんらかので、デフォルトのPowerShellモジュールリポジトリPSGalleryがされた。するがあります。これがコマンドです。

Register-PSRepository -Default

モジュールをでする

Find-Module -Name <Name>

モジュールをでインストールする

Install-Module -Name <name>

のとバージョンをモジュールからアンインストールする

Uninstall-Module -Name <Name> -RequiredVersion <Version>

モジュールをでする

Update-Module -Name <Name>

https://riptutorial.com/ja/home 142

Page 163: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

50: ハッシュテーブル

ハッシュテーブルは、キーをにマッピングするです。はハッシュテーブルをしてください。

ハッシュテーブルにするなは、 Splattingです。これは、りしのパラメータでのびしをうににです。

Examples

ハッシュテーブルの

のHashTableをする

$hashTable = @{}

データきのHashTableの

$hashTable = @{ Name1 = 'Value' Name2 = 'Value' Name3 = 'Value3' }

キーでハッシュテーブルのにアクセスします。

ハッシュテーブルをし、キーによるにアクセスする

$hashTable = @{ Key1 = 'Value1' Key2 = 'Value2' } $hashTable.Key1 #output Value1

プロパティになをむキーにアクセスする

$hashTable = @{ 'Key 1' = 'Value3' Key2 = 'Value4' } $hashTable.'Key 1' #Output Value3

https://riptutorial.com/ja/home 144

Page 164: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

ハッシュテーブルをループする

$hashTable = @{ Key1 = 'Value1' Key2 = 'Value2' } foreach($key in $hashTable.Keys) { $value = $hashTable.$key Write-Output "$key : $value" } #Output Key1 : Value1 Key2 : Value2

のハッシュテーブルにキーのペアをする

たとえば、をして、 "Value2"の "Key2"キーをハッシュテーブルにするをにします。

$hashTable = @{ Key1 = 'Value1' } $hashTable += @{Key2 = 'Value2'} $hashTable #Output Name Value ---- ----- Key1 Value1 Key2 Value2

たとえば、Addメソッドをしてハッシュテーブルに "Value2"の "Key2"キーをするをにします。

$hashTable = @{ Key1 = 'Value1' } $hashTable.Add("Key2", "Value2") $hashTable #Output Name Value ---- ----- Key1 Value1 Key2 Value2

キーとキーとのペアをする

キーによる

foreach ($key in $var1.Keys) { $value = $var1[$key]

https://riptutorial.com/ja/home 145

Page 165: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# or $value = $var1.$key }

キーとのペアをする

foreach ($keyvaluepair in $var1.GetEnumerator()) { $key1 = $_.Key1 $val1 = $_.Val1 }

のハッシュテーブルからキーのペアをする

たとえば、removeをしてハッシュテーブルから "Value2"の "Key2"キーをするをにします。

$hashTable = @{ Key1 = 'Value1' Key2 = 'Value2' } $hashTable.Remove("Key2", "Value2") $hashTable #Output Name Value ---- ----- Key1 Value1

オンラインでハッシュテーブルをむ https://riptutorial.com/ja/powershell/topic/8083/ハッシュテーブル

https://riptutorial.com/ja/home 146

Page 166: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

51: パラメータセット

パラメータセットは、なパラメータのみわせをするため、または1つまたはのパラメータがされたときにパラメータのをするためにされます。

このでは、パラメータセットのとをします。

Examples

なパラメータセット

function myFunction { param( # If parameter 'a' is used, then 'c' is mandatory # If parameter 'b' is used, then 'c' is optional, but allowed # You can use parameter 'c' in combination with either 'a' or 'b' # 'a' and 'b' cannot be used together [parameter(ParameterSetName="AandC", mandatory=$true)] [switch]$a, [parameter(ParameterSetName="BandC", mandatory=$true)] [switch]$b, [parameter(ParameterSetName="AandC", mandatory=$true)] [parameter(ParameterSetName="BandC", mandatory=$false)] [switch]$c ) # $PSCmdlet.ParameterSetName can be used to check which parameter set was used Write-Host $PSCmdlet.ParameterSetName } # Valid syntaxes myFunction -a -c # => "Parameter set : AandC" myFunction -b -c # => "Parameter set : BandC" myFunction -b # => "Parameter set : BandC" # Invalid syntaxes myFunction -a -b # => "Parameter set cannot be resolved using the specified named parameters." myFunction -a # => "Supply values for the following parameters: # c:"

のものがされているときにパルメータのをするためのパラメータセット。

たとえば、パラメータUserがされているは、パラメータPasswordのをします。 そしてその

https://riptutorial.com/ja/home 147

Page 167: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Function Do-Something { Param ( [Parameter(Mandatory=$true)] [String]$SomeThingToDo, [Parameter(ParameterSetName="Credentials", mandatory=$false)] [String]$Computername = "LocalHost", [Parameter(ParameterSetName="Credentials", mandatory=$true)] [String]$User, [Parameter(ParameterSetName="Credentials", mandatory=$true)] [SecureString]$Password ) #Do something } # This will not work he will ask for user and password Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' -ComputerName # This will not work he will ask for password Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' -User

パルメータのみわせをするパラメータセット

Function Do-Something { Param ( [Parameter(Mandatory=$true)] [String]$SomeThingToDo, [Parameter(ParameterSetName="Silently", mandatory=$false)] [Switch]$Silently, [Parameter(ParameterSetName="Loudly", mandatory=$false)] [Switch]$Loudly ) #Do something } # This will not work because you can not use the combination Silently and Loudly Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' -Silently -Loudly

オンラインでパラメータセットをむ https://riptutorial.com/ja/powershell/topic/6598/パラメータセット

https://riptutorial.com/ja/home 148

Page 168: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

52: ビルトイン

PowerShellには、さまざまなな「」みみがされています。のはなでのみされ、そののはグローバルでできます。

Examples

$ PSScriptRoot

Get-ChildItem -Path $PSScriptRoot

このでは、スクリプトファイルがするフォルダからアイテムディレクトリおよびファイルのリストをします。

$PSScriptRootは、PowerShellコードファイルのからするは$nullです。 PowerShellスクリプトでされた、スクリプトファイルをむディレクトリへのファイルシステムパスがにされます。

Windows PowerShell 2.0では、このはスクリプトモジュール.psm1でのみです。 Windows

PowerShell 3.0、すべてのスクリプトでです。

$ Args

$Args

、スクリプト、またはスクリプトブロックにされるされていないパラメータやパラメータのをみます。をするときは、paramキーワードをするか、のにカッコでんだパラメータのカンマりリストをしてパラメータをできます。

イベントアクションでは、$ Argsには、のイベントのイベントをすオブジェクトがまれています。このは、イベントコマンドのActionブロックにのみされます。こののは、Get-EventがすPSEventArgsオブジェクトSystem.Management.Automation.PSEventArgsのSourceArgsプロパティにもあります。

$ PSItem

Get-Process | ForEach-Object -Process { $PSItem.Name }

$_じです。パイプラインオブジェクトにのオブジェクトがまれています。このは、すべてのオブジェクトまたはパイプラインのされたオブジェクトにしてアクションをするコマンドでできます

https://riptutorial.com/ja/home 149

Page 169: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$

Get-Process -Name doesnotexist Write-Host -Object "Was the last operation successful? $?"

ののステータスがまれます。のがしたはTRUEをし、したはFALSEをします。

$エラー

Get-Process -Name doesnotexist Write-Host -Object ('The last error that occurred was: {0}' -f $error[0].Exception.Message)

のエラーをすエラーオブジェクトのをみます。のエラーは、$ Error [0]ののエラーオブジェクトです。

エラーが$ Errorにされないようにするには、ErrorActionパラメーターにIgnoreというをします。については、about_CommonParameters http://go.microsoft.com/fwlink/?LinkID=113216をしてください 。

オンラインでビルトインをむ https://riptutorial.com/ja/powershell/topic/8732/ビルトイン

https://riptutorial.com/ja/home 150

Page 170: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

53: ヘルプシステムのGet-Helpは、PowerShellのヘルプトピックをむためのコマンドレットです。

もっとむTechNet

Examples

ヘルプシステムの

3.0

PowerShell 3.0から、のコマンドレットをしてオフラインヘルプドキュメントをダウンロードおよびできます。

Update-Help

のコンピュータまたはインターネットにされていないコンピュータのヘルプをするには

ヘルプファイルをしてコンピュータでのコマンドをします

Save-Help -DestinationPath \\Server01\Share\PSHelp -Credential $Cred

くのコンピュータをリモートでするには

Invoke-Command -ComputerName (Get-Content Servers.txt) -ScriptBlock {Update-Help -SourcePath \\Server01\Share\Help -Credential $cred}

Get-Helpの

Get-HelpをしてPowerShellのヘルプをできます。コマンドレット、、プロバイダ、またはそののトピックをできます。

ジョブにするヘルプドキュメントをするには、のコマンドをします。

Get-Help about_Jobs

ワイルドカードをしてトピックをできます。タイトルがabout_でまるなヘルプトピックをするには、 about_にしてください。

Get-Help about_*

Select-Objectヘルプがだったは、をします。

Get-Help Select-Object

https://riptutorial.com/ja/home 151

Page 171: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

エイリアスのhelpやmanうこともできます。

ヘルプトピックのオンラインの

をして、オンラインヘルプドキュメントにアクセスできます。

Get-Help Get-Command -Online

のコマンドレットのをします。

Get-Help Get-Command -Examples

なヘルプページの

トピックのなドキュメントをしてください。

Get-Help Get-Command -Full

のパラメータのヘルプの

をして、のパラメータのヘルプをできます。

Get-Help Get-Content -Parameter Path

オンラインでヘルプシステムのをむ https://riptutorial.com/ja/powershell/topic/5644/ヘルプシステムの

https://riptutorial.com/ja/home 152

Page 172: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

54: マネージコードのめみC| VB

このトピックでは、PowerShellスクリプトでCまたはVB .NET Managedコードをスクリプトしてするについてにします。このトピックでは、Add-Typeコマンドレットのすべてのについてしていません。

Add-Typeコマンドレットのについては、MSDNのドキュメント5.1をしてください。https :

//msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/add-タイプ

パラメーター

パラメータ

-TypeDefinition <String_>

コードをとしてけれる

- <String_>されたコードlanguage.AcceptedをしますCSharp、CSharpVersion3、CSharpVersion2、VisualBasic、JScript

されたタイプをする

PowerShellのそれのバージョンでは、Remove-TypeDataがPowerShellコマンドレットライブラリにされました。このライブラリは、セッションののをにします。このコマンドレットのについては、こちらをしてください。https : //msdn.microsoft.com/en-us/powershell/reference/4.0/microsoft.powershell.utility/remove-typedata

CSharpと.NETの

.NETでののために、Cのなるバージョンはのにするサポートのレベルがかなりになることはうまでもない。

Powershell 1.0および/または-Language CSharpをする、マネージドコードは、Generics、Linq、Lambdaなど、Cがにえていないくのにけている.NET 2.0をします。これにえて、ながあります。これは、C/ .NETのそれのバージョンでデフォルトパラメータでされます。

Examples

Cの

https://riptutorial.com/ja/home 153

Page 173: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

このでは、なCをPowerShellスクリプトにめみ、それをrunspace / sessionにし、コードをPowerShellでするをします。

$code = " using System; namespace MyNameSpace { public class Responder { public static void StaticRespond() { Console.WriteLine("Static Response"); } public void Respond() { Console.WriteLine("Instance Respond"); } } } "@ # Check the type has not been previously added within the session, otherwise an exception is raised if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type) { Add-Type -TypeDefinition $code -Language CSharp; } [MyNameSpace.Responder]::StaticRespond(); $instance = New-Object MyNameSpace.Responder; $instance.Respond();

VB.NETの

このでは、なCをPowerShellスクリプトにめみ、それをrunspace / sessionにし、コードをPowerShellでするをします。

$code = @" Imports System Namespace MyNameSpace Public Class Responder Public Shared Sub StaticRespond() Console.WriteLine("Static Response") End Sub Public Sub Respond() Console.WriteLine("Instance Respond") End Sub End Class End Namespace "@ # Check the type has not been previously added within the session, otherwise an exception is

https://riptutorial.com/ja/home 154

Page 174: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

raised if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type) { Add-Type -TypeDefinition $code -Language VisualBasic; } [MyNameSpace.Responder]::StaticRespond(); $instance = New-Object MyNameSpace.Responder; $instance.Respond();

オンラインでマネージコードのめみC| VBをむ https://riptutorial.com/ja/powershell/topic/9823/マネージコードのめみ-c---vb-

https://riptutorial.com/ja/home 155

Page 175: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

55: モジュール、スクリプト、

PowerShellモジュールは、システム、DBA、およびにをもたらします 。にとスクリプトをするであるかどうか。

Powershell は、りしコードをけることです。 [PS] [1] [1] PowerShellをしてください。

PowerShellスクリプトは、タスクをするためにされます。タスクは、コマンドラインシェルと、.NET Frameworkにされたするコマンドレットでされています。

Examples

は、いいなコードをするためにされるコードのきブロックです。これは、コードのコードのをけるためやのスクリプトのでのにつようにモジュールのとしてされるスクリプトにまれています。

がにつかもしれないシナリオ

のグループのをする•プロセスをするためのレポートをする•コンピュータにpingをしてc$ -shareにアクセスして、コンピュータが「」であるかどうかをテストするをします

は、 functionキーワードをしてされ、そのに1のとがびされたときにされるコードをむスクリプトブロックがきます。

function NameOfFunction { Your code }

デモ

function HelloWorld { Write-Host "Greetings from PowerShell!" }

> HelloWorld Greetings from PowerShell!

スクリプト

スクリプトは、スクリプトの.ps1にされるPowerShellコマンドをむファイル.ps1をつテキストファイルです。スクリプトはされたファイルなので、コンピュータでにできます。

https://riptutorial.com/ja/home 156

Page 176: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

スクリプトはのをするためによくかれています。

のメンテナンスタスクをする•コンピュータにソリューション/アプリケーションをインストールしてするには•

デモ

MyFirstScript.ps1

Write-Host "Hello World!" 2+2

のコマンドをして、ファイルへのパスをしてスクリプトをできます。

パス、ex。 c:\MyFirstScript.ps1•

PowerShellコンソールののディレクトリがC:\は、パス .\MyFirstScript.ps1•

> .\MyFirstScript.ps1 Hello World! 4

スクリプトはモジュールをインポートしたり、のなどをすることもできます。

MySecondScript.ps1

function HelloWorld { Write-Host "Greetings from PowerShell!" } HelloWorld Write-Host "Let's get started!" 2+2 HelloWorld

> .\MySecondScript.ps1 Greetings from PowerShell! Let's get started! 4 Greetings from PowerShell!

モジュール

モジュールは、のPowerShellユーザーににしたり、のスクリプトやコンソールでできるするなまたはコマンドレットのです。モジュールは、それのディレクトリにされ、のでされます。

をむファイル.psm1つ1つのコードファイル、またはコマンドレットをむバイナリアセンブリ .dll

モジュールの、バージョン、、、する/コマンドレットなどをするモジュールマニフェスト.psd1

https://riptutorial.com/ja/home 157

Page 177: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

それをむのがまれています。、スクリプトなど•

モジュールの

データセットにするをする/コマンドレットをむモジュール•

データベースのとのためのモジュール•

PowerShellがモジュールをつけてインポートするのをにするために、 $env:PSModulePathされているのPowerShellモジュールのの1つにされることがよくあります。

デモ

のモジュールの1つにインストールされているモジュールをします。

Get-Module -ListAvailable

のモジュールをインポートします。 Hyper-Vモジュール

Import-Module Hyper-V

モジュールでなコマンドをするex。 Microsoft.PowerShell.Archive - モジュール

> Import-Module Microsoft.PowerShell.Archive > Get-Command -Module Microsoft.PowerShell.Archive CommandType Name Version Source ----------- ---- ------- ------ Function Compress-Archive 1.0.1.0 Microsoft.PowerShell.Archive Function Expand-Archive 1.0.1.0 Microsoft.PowerShell.Archive

なは、コマンドレットとじようにします。 PowerShell ISEには、2つのなのスケルトンがまれています。これらのメニューにアクセスするには、、コードスニペット、またはCtrl + Jをします。 PS 3.0、のバージョンはなるがあります

なには、

Get-Helpしてアクセスなみみのカスタマイズされたヘルプ•をコマンドレットのようにさせる[CmdletBinding]をできます•

パラメータオプション•

シンプルバージョン

<# .Synopsis Short description .DESCRIPTION

https://riptutorial.com/ja/home 158

Page 178: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet #> function Verb-Noun { [CmdletBinding()] [OutputType([int])] Param ( # Param1 help description [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $Param1, # Param2 help description [int] $Param2 ) Begin { } Process { } End { } }

<# .Synopsis Short description .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES General notes .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> function Verb-Noun { [CmdletBinding(DefaultParameterSetName='Parameter Set 1', SupportsShouldProcess=$true,

https://riptutorial.com/ja/home 159

Page 179: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PositionalBinding=$false, HelpUri = 'http://www.microsoft.com/', ConfirmImpact='Medium')] [OutputType([String])] Param ( # Param1 help description [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, Position=0, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidateCount(0,5)] [ValidateSet("sun", "moon", "earth")] [Alias("p1")] $Param1, # Param2 help description [Parameter(ParameterSetName='Parameter Set 1')] [AllowNull()] [AllowEmptyCollection()] [AllowEmptyString()] [ValidateScript({$true})] [ValidateRange(0,5)] [int] $Param2, # Param3 help description [Parameter(ParameterSetName='Another Parameter Set')] [ValidatePattern("[a-z]*")] [ValidateLength(0,15)] [String] $Param3 ) Begin { } Process { if ($pscmdlet.ShouldProcess("Target", "Operation")) { } } End { } }

オンラインでモジュール、スクリプト、をむ https://riptutorial.com/ja/powershell/topic/5755/モジュール-スクリプト-

https://riptutorial.com/ja/home 160

Page 180: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

56: ループ

ループとは、のにするまでにりされるのです。あなたのプログラムがコードブロックをりしできるようにすることは、プログラミングのもではあるがなタスクの1つです。ループをすると、になステートメントをくことができます。にした、のはのシーケンシャルに「」するか、またはループにします。

<Initialization>; <Condition>; <Repetition>{<Script_Block>}•

<コレクション> | Foreach-Object {<Script_Block_with _ $ __ as_current_item>}•

foreach<Collection>の<Item>{<Script_Block>}•

while<>{<Script_Block>}•

while {<Script_Block>} while<Condition>•

<Condition>まで{{Script_Block>}してください•

<コレクション> .foreach{<Script_Block_with _ $ __ as_current_item>}•

フォアハPowerShellでforeach-loopをするには、のがあり、それぞれのとがあります。

Foreachステートメント

。コレクションにされているにもしています。

パイプラインまたはなし

ForEachメソッド

Foreach-Objectとじスクリプトブロックですが、です。コレクションにされているにもしています。パイプラインをサポートします。

パイプラインはサポートされていません。 PowerShell 4.0が

Foreach-Objectコマンドレット

パイプラインをサポートします。のとのためのとスクリプトブロックをサポートします。もなソリューション。

もい

パフォーマンス

$foreach = Measure-Command { foreach ($i in (1..1000000)) { $i * $i } } $foreachmethod = Measure-Command { (1..1000000).ForEach{ $_ * $_ } }

https://riptutorial.com/ja/home 161

Page 181: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$foreachobject = Measure-Command { (1..1000000) | ForEach-Object { $_ * $_ } } "Foreach: $($foreach.TotalSeconds)" "Foreach method: $($foreachmethod.TotalSeconds)" "ForEach-Object: $($foreachobject.TotalSeconds)" Example output: Foreach: 1.9039875 Foreach method: 4.7559563 ForEach-Object: 10.7543821

Foreach-Objectはもいですが、パイプラインサポートは、にアイテムをできるようにファイルのみり、データのなどちます。これは、にすべてのデータをメモリにロードするがないため、きなデータといメモリでするににです。

Examples

にとって

for($i = 0; $i -le 5; $i++){ "$i" }

forループのないは、ののサブセットをすることです。ほとんどの、のすべてのをするは、foreach

のをしてください。

フォアハ

ForEachは、PowerShellでは2つのなるをちます。 1つはキーワードで、もう1つはForEach-Object

コマンドレットのエイリアスです。ここではについてします。

このでは、のすべてのをコンソールホストにするをします。

$Names = @('Amy', 'Bob', 'Celine', 'David') ForEach ($Name in $Names) { Write-Host "Hi, my name is $Name!" }

このでは、ForEachループのをキャプチャするをします。

$Numbers = ForEach ($Number in 1..20) { $Number # Alternatively, Write-Output $Number }

のとに、このではループをするにをするをします。

https://riptutorial.com/ja/home 162

Page 182: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$Numbers = @() ForEach ($Number in 1..20) { $Numbers += $Number }

whileループはをし、trueならアクションをします。がとされるり、アクションはききされます。

while(condition){ code_block }

のでは、10から0にカウントダウンするループをします

$i = 10 while($i -ge 0){ $i $i-- }

Do -Whileループとはなり、はアクションのののにされます。がfalseとされた、アクションはされません。

をするとき、PowerShellはりオブジェクトのをtrueとしています。これはいくつかのでできますが、はプロセスをするです。このでは、メモプロセスがされ、そのプロセスがされているり、のシェルをスリープします。メモインスタンスをでじると、whileがし、ループがれます。

Start-Process notepad.exe while(Get-Process notepad -ErrorAction SilentlyContinue){ Start-Sleep -Milliseconds 500 }

ForEach-Object

ForEach-ObjectコマンドレットはforeachステートメントとにForEach-Objectしますが、パイプラインからのをけります。

$object | ForEach-Object { code_block }

$names = @("Any","Bob","Celine","David") $names | ForEach-Object { "Hi, my name is $_!" }

Foreach-Objectは、2つのデフォルトのforeachと% があります。 foreachがforeachとされるがあるた

https://riptutorial.com/ja/home 163

Page 183: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

め、もなものは%です。

$names | % { "Hi, my name is $_!" } $names | foreach { "Hi, my name is $_!" }

ない

Foreach-Objectは、パイプラインをするようにされたコマンドレットであるため、わりのforeachソリューションからっています。このため、cmdletやなとに、3つのスクリプトブロックをサポートしています。

Begin パイプラインからしたアイテムをループするにします。、ループでするの、の、のオープンデータベース、Web +などなどにされます。

プロセス パイプラインからしたアイテムごとに1されます。コードブロックの ""です。これは、パラメータがされていないののでされるデフォルトです。

すべてのアイテムをしたに1します。、をじたり、レポートをするためにされます。•

"Any","Bob","Celine","David" | ForEach-Object -Begin { $results = @() } -Process { #Create and store message $results += "Hi, my name is $_!" } -End { #Count messages and output Write-Host "Total messages: $($results.Count)" $results }

Do-Loopは、コードブロックをなくとも1はにしたいにです。 Do-loopは、コードブロックをするにするwhile-loopとはなり、コードブロックをしたのをします。

do-loopsはの2つのでできます。

がたされているループする

Do { code_block } while (condition)

がになるまでループします。つまり、がfalseのときにループします。

Do {

https://riptutorial.com/ja/home 164

Page 184: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

code_block } until (condition)

$i = 0 Do { $i++ "Number $i" } while ($i -ne 3) Do { $i++ "Number $i" } until ($i -eq 3)

Do-WhileとDo-Untilはループです。じコードにある、はになります。のは、このをしています。

ForEachメソッド

4.0

わりForEach-Objectレット、ここでするもあるForEachようなので、オブジェクトには

(1..10).ForEach({$_ * $_})

または - にじて、スクリプトブロックのまわりのをすることができます

(1..10).ForEach{$_ * $_}

どちらものになります

1 4 9 16 25 36 49 64 81 100

する

ContinueはFor 、 ForEach 、 WhileおよびDoループでForEach Doます。ループののをスキップし、ものループのにジャンプします。

$i =0 while ($i -lt 20) {

https://riptutorial.com/ja/home 165

Page 185: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$i++ if ($i -eq 7) { continue } Write-Host $I }

はコンソールに1から20をしますが、7をします。

パイプラインループをするは、 Continueではなく「 return 」をするがあります。

ブレーク

breakは、すぐにプログラムループをします。 For 、 ForEach 、 WhileおよびDoループまたはSwitch

ステートメントでできます。

$i = 0 while ($i -lt 15) { $i++ if ($i -eq 7) {break} Write-Host $i }

は15にカウントされますが、7にするとすぐにします。

パイプラインループをする、 breakはcontinueようにします。パイプラインループのbreakをシミュレートbreakは、のロジック、コマンドレットなどをみむがあります。 breakをするがあるは、パイプラインループをするがです。

ブレークラベル

Breakは、ループのインスタンスのにかれたラベルをびすこともできます。

$i = 0 :mainLoop While ($i -lt 15) { Write-Host $i -ForegroundColor 'Cyan' $j = 0 While ($j -lt 15) { Write-Host $j -ForegroundColor 'Magenta' $k = $i*$j Write-Host $k -ForegroundColor 'Green' if ($k -gt 100) { break mainLoop } $j++ } $i++ }

このコードは、 $iを8 、 $jを13にやし、 $kが104ます。 $kが100えているので、コードはのループからけします。

オンラインでループをむ https://riptutorial.com/ja/powershell/topic/1067/ループ

https://riptutorial.com/ja/home 166

Page 186: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

57: パラメータパラメーターはのコマンドレットでできますつまり、をcmdlet [ CmdletBinding() ]としてマークすると、これらのパラメーターはすべてになります。

すべてのなパラメータのをしますエイリアスは、するパラメータののにあります。

-Debug (db) -ErrorAction (ea) -ErrorVariable (ev) -InformationAction (ia) # introduced in v5 -InformationVariable (iv) # introduced in v5 -OutVariable (ov) -OutBuffer (ob) -PipelineVariable (pv) -Verbose (vb) -WarningAction (wa) -WarningVariable (wv) -WhatIf (wi) -Confirm (cf)

Examples

ErrorActionパラメータ

なはContinue | Ignore | Inquire | SilentlyContinue | Stop | Suspend 。

このパラメータのは、コマンドレットがエラーたとえばWrite-Errorからされたもの;エラーのについては[ トピック ]ををするをします。

デフォルトこのパラメーターをしたはContinueです。

-ErrorActionをこのオプションはエラーメッセージをし、をします。

PS C:\> Write-Error "test" -ErrorAction Continue ; Write-Host "Second command"

-ErrorActionする

https://riptutorial.com/ja/home 167

Page 187: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

このオプションはエラーメッセージをせず、をします。また、 $Errorに$Errorがされません。 このオプションはv3でされました。

PS C:\> Write-Error "test" -ErrorAction Ignore ; Write-Host "Second command"

-ErrorAction Inquire

このオプションをすると、エラーメッセージがされ、ユーザーはするアクションをするようめられます。

PS C:\> Write-Error "test" -ErrorAction Inquire ; Write-Host "Second command"

-ErrorActionはってけますこのオプションはエラーメッセージをせず、をします。すべてのエラーは$Errorにされます。

PS C:\> Write-Error "test" -ErrorAction SilentlyContinue ; Write-Host "Second command"

-ErrorAction Stop

このオプションはエラーメッセージをし、をしません。

PS C:\> Write-Error "test" -ErrorAction Stop ; Write-Host "Second command"

https://riptutorial.com/ja/home 168

Page 188: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

-ErrorAction Suspend

Powershellワークフローでのみできます。コマンドをすると、コマンドがエラーになった、ワークフローはされます。これにより、そのようなエラーのがになり、ワークフローをできるようになります。ワークフローシステムのについては、[まだされていないトピック]をしてください。

オンラインでパラメータをむ https://riptutorial.com/ja/powershell/topic/5951/パラメータ

https://riptutorial.com/ja/home 169

Page 190: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

59: セット

セットとはでもよいアイテムのです。これらのセットでするがあるはすべて、 セットであり、はセットともばれます 。セットには、、、、などがまれます。

グループオブジェクト•

グループオブジェクト - プロパティ<propertyName>•

グループオブジェクト - プロパティ<propertyName>、<propertyName2>•

グループオブジェクト - プロパティ<propertyName> -CaseSensitive•

グループオブジェクト - プロパティ<propertyName> - <culture>•

グループオブジェクト - プロパティ<ScriptBlock>•

ソートオブジェクト•

Sort-Object -Property <プロパティ>•

Sort-Object -Property <ScriptBlock>•

Sort-Object -Property <プロパティ>、<プロパティ2>•

Sort-Object -Property <propertyObject> -CaseSensitive•

ソートオブジェクト - プロパティ<propertyObject> - •

Sort-Object -Property <propertyObject> - ユニーク•

Sort-Object -Property <propertyObject> - カルチャ<culture>•

Examples

フィルタリングWhere-Object / where /

をしてをフィルタリングする

Where-Object where ?

$names = @( "Aaron", "Albert", "Alphonse","Bernie", "Charlie", "Danny", "Ernie", "Frank")

https://riptutorial.com/ja/home 171

Page 191: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$names | Where-Object { $_ -like "A*" } $names | where { $_ -like "A*" } $names | ? { $_ -like "A*" }

アーロン

アルバート

アルフォンス

けソートオブジェクト/ソート

をまたはにソートする

Sort-Object sort

$names = @( "Aaron", "Aaron", "Bernie", "Charlie", "Danny" )

ソートがデフォルトです。

$names | Sort-Object $names | sort

アーロン

アーロン

バーニー

チャーリー

ダニー

をリクエストするには

$names | Sort-Object -Descending $names | sort -Descending

ダニー

チャーリー

バーニー

アーロン

アーロン

をってソートすることができます。

$names | Sort-Object { $_.length }

アーロン

https://riptutorial.com/ja/home 172

Page 192: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

アーロン

ダニー

バーニー

チャーリー

グループグループ - オブジェクト/グループ

にづいてをグループできます。

Group-Object group

$names = @( "Aaron", "Albert", "Alphonse","Bernie", "Charlie", "Danny", "Ernie", "Frank") $names | Group-Object -Property Length $names | group -Property Length

カウント グループ

4 5 {アーロン、ダニー、アーニー、フランク}

2 6 {アルバート、バーニー}

1 8 {Alphonse}

1 7 {チャーリー}

プロジェクションSelect-Object / select

をすると、オブジェクトののメンバーをしたり、すべてのをしたり、オブジェクトのをしたりすることができます

Select-Object select

プロパティのサブセットの

$dir = dir "C:\MyFolder" $dir | Select-Object Name, FullName, Attributes $dir | select Name, FullName, Attributes

フルネーム

イメージ C\ MyFolder \ Images ディレクトリ

data.txt C\ MyFolder \ data.txt アーカイブ

https://riptutorial.com/ja/home 173

Page 193: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

フルネーム

source.c C\ MyFolder \ source.c アーカイブ

のをし、すべてのプロパティをする

$d | select -first 1 *

PSPath

PSParentPath

PSChildName

PSDrive

PSProvider

PSIsContainer

BaseName

モード

する

ルート

フルネーム

CreationTime

CreationTimeUtc

LastAccessTime

LastAccessTimeUtc

LastWriteTime

LastWriteTimeUtc

オンラインでセットをむ https://riptutorial.com/ja/powershell/topic/1557/セット

https://riptutorial.com/ja/home 174

Page 194: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

60: ファイルの

Examples

コンソールアプリケーション

PS> console_app.exe PS> & console_app.exe PS> Start-Process console_app.exe

GUIアプリケーション

PS> gui_app.exe (1) PS> & gui_app.exe (2) PS> & gui_app.exe | Out-Null (3) PS> Start-Process gui_app.exe (4) PS> Start-Process gui_app.exe -Wait (5)

GUIアプリケーションはのプロセスでし、すぐにPowerShellホストにをします。によっては、のPowerShellステートメントをするにをするアプリケーションがになることがあります。これは、アプリケーションを$ null3にパイプするか、-Waitスイッチ5でStart-Processをすることでできます。

コンソールストリーム

PS> $ErrorActionPreference = "Continue" (1) PS> & console_app.exe *>&1 | % { $_ } (2) PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.ErrorRecord] } (3) PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.WarningRecord] } (4) PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.VerboseRecord] } (5) PS> & console_app.exe *>&1 (6) PS> & console_app.exe 2>&1 (7)

ストリーム2には、System.Management.Automation.ErrorRecordオブジェクトがまれています。 git.exeのようなアプリケーションのには、ので「エラーストリーム」をしているものがありますが、ずしもエラーではありません。この、コードをべて、エラーストリームをエラーとしてするがあるかどうかをするのがです。

PowerShellは、、エラー、、、デバッグ、のストリームをします。ネイティブアプリケーションでは、にのストリームのみをします。、エラー、。

PowerShell 5では、すべてのストリームを/ストリーム6にリダイレクトできます。

のPowerShellバージョンでは、のストリームのみを/ストリーム7にリダイレクトできます。このでは、「エラーストリーム」がストリームにリダイレクトされます。

https://riptutorial.com/ja/home 175

Page 195: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

コード

PS> $LastExitCode PS> $? PS> $Error[0]

これらは、PowerShellのみみで、のエラーにするをします。 $LastExitCodeは、されたのネイティブアプリケーションのなコードです。 $? $Error[0]はPowerShellによってされたのエラーレコードです。

オンラインでファイルのをむ https://riptutorial.com/ja/powershell/topic/7707/ファイルの

https://riptutorial.com/ja/home 176

Page 196: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

61: するの

Examples

な - WindowsFeatureをにする

configuration EnableIISFeature { node localhost { WindowsFeature IIS { Ensure = “Present” Name = “Web-Server” } } }

PowershellEnableIISFeatureでこのをすると、localhost.mofファイルがされます。これは、マシンでできる「コンパイルみ」です。

ローカルホストのDSCをテストするには、のコードをします。

Start-DscConfiguration -ComputerName localhost -Wait

リモートマシンでのDSCmofの

リモートマシンでDSCをすることは、ほぼじくらいです。すでにPowershellのリモーティングまたはなWSMANをセットアップしているとします。

$remoteComputer = "myserver.somedomain.com" $cred = (Get-Credential) Start-DSCConfiguration -ServerName $remoteComputer -Credential $cred -Verbose

Nbあなたのローカルマシンのあなたのノードのをコンパイルしたとしますをするにファイルmyserver.somedomain.com.mofがするとします

psd1データファイルをローカルにインポートする

によっては、Powershellデータファイルをテストして、ノードとサーバーをするとです。

Powershell 5WMF5は、Import-PowerShellDataFileとばれるこのをしました。

$data = Import-PowerShellDataFile -path .\MydataFile.psd1 $data.AllNodes

https://riptutorial.com/ja/home 177

Page 197: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

なDSCリソースのリスト

オーサリングノードでなDSCリソースをするには

Get-DscResource

これにより、オーサリングノードにインストールされているすべてのモジュールPSModulePath

にあるモジュールのすべてのリソースがされます。

WMF 5のオンラインソースPSGallery ++にあるなDSCリソースをすべてするには

Find-DSCResource

DSCでするためのリソースのインポート

のリソースをするには、そのリソースをにインポートするがあります。あなたのコンピュータにインストールするだけで、あなたはのうちにリソースをすることはできません。

Import-DscResourceをしてリソースをインポートします。

PSDesiredStateConfigurationリソースとFileリソースをインポートするの

Configuration InstallPreReqs { param(); # params to DSC goes here. Import-DscResource PSDesiredStateConfiguration File CheckForTmpFolder { Type = 'Directory' DestinationPath = 'C:\Tmp' Ensure = "Present" } }

DSCリソースをさせるには、をするときにターゲットマシンにモジュールをインストールするがあります。それらをインストールしていないと、はします。

オンラインでするのをむ https://riptutorial.com/ja/powershell/topic/5662/するの

https://riptutorial.com/ja/home 178

Page 198: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

62:

"ダブルクォート"•

'リテラル'•

@ " Here-string "@

@ ' リテラルのhere-string '@

はテキストをすオブジェクトです。

Examples

なの

はでむことでされます。でまれたはとをできます。

$myString = "Some basic text" $mySecondString = "String with a $variable"

のでをするには、エスケープbacktick ` をしてエスケープするがあります。でまれたので、をうことができます。

$myString = "A `"double quoted`" string which also has 'single quotes'."

リテラルリテラルは、やをしないです。これは、をしてされます。

$myLiteralString = 'Simple text including special characters (`n) and a $variable-reference'

リテラルのでをするには、またはリテラルhere-stringをします。qutoはリテラルでにできます

$myLiteralString = 'Simple string with ''single quotes'' and "double quotes".'

フォーマット

https://riptutorial.com/ja/home 179

Page 199: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$hash = @{ city = 'Berlin' } $result = 'You should really visit {0}' -f $hash.city Write-Host $result #prints "You should really visit Berlin"

は、 -fまたはstatic [String]::Format(string format, args) .NETメソッドでできます。

PowerShellでのをするには、のがあります。

をキャリッジリターンやにでするか、 NewLineをしてシステムの ""をすることがNewLineます

"Hello`r`nWorld" "Hello{0}World" -f [environment]::NewLine

をしながらをするをじるに

"Hello World"

here-stringをします。 これがもなです。

@" Hello World "@

Here-string

ここでは、のをするときにがにです。のマルチラインとしたのの1つは、バックティックをしてをエスケープしなくてもできるということです。

Here-string

ここでは、でまる@"とでわる"@それのに"@さえではない/タブ、ののでなければなりません 。

@" Simple Multiline string with "quotes" "@

リテラルのhere-string

のリテラルのようにをしたくないは、をしてリテラルのhere-stringをすることもできます。

https://riptutorial.com/ja/home 180

Page 200: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

@' The following line won't be expanded $(Get-Date) because this is a literal here-string '@

ののでまれたのをしてをすることができます。これはプロパティではしません。

$string1 = "Power" $string2 = "Shell" "Greetings from $string1$string2"

+をする+をしてをすることもできます。

$string1 = "Greetings from" $string2 = "PowerShell" $string1 + " " + $string2

これはオブジェクトのプロパティでもします。

"The title of this console is '" + $host.Name + "'"

サブの$()の/は、でできます。これは、オブジェクトのpropetiesにアクセスするときやなをするときにです。サブには、セミコロンでられたのステートメントをめることができます;

"Tomorrow is $((Get-Date).AddDays(1).DayOfWeek)"

でまれたのでされる、エスケープバックティック` はをします。

`0 #Null `a #Alert/Beep `b #Backspace `f #Form feed (used for printer output) `n #New line `r #Carriage return `t #Horizontal tab `v #Vertical tab (used for printer output)

https://riptutorial.com/ja/home 181

Page 201: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

> "This`tuses`ttab`r`nThis is on a second line" This uses tab This is on a second line

なをつをエスケープすることもできます

`# #Comment-operator `$ #Variable operator `` #Escape character `' #Single quote `" #Double quote

オンラインでをむ https://riptutorial.com/ja/powershell/topic/5124/

https://riptutorial.com/ja/home 182

Page 202: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

63: のクラスの

これらのクラスは、ステートを1つのでしないメソッドとプロパティのライブラリです。するはありません。にしてください。これらのクラスやメソッドは、、、されないため、クラスとばれます。クラスをでんでクラスをできます。

Examples

にしいGUIDをする

[class] :: MethodargsをしてPowerShellでの.NETクラスをにする

PS C:\> [guid]::NewGuid() Guid ---- 8874a185-64be-43ed-a64c-d2fe4b6e31bc

に、PowerShell 5では、 New-Guidコマンドレットをできます。

PS C:\> New-Guid Guid ---- 8874a185-64be-43ed-a64c-d2fe4b6e31bc

GUIDを[String]のみとしてするには、 .Guidプロパティをします。

[guid]::NewGuid().Guid

.NETのクラスの

.Net Mathクラスをしてをうことができます[System.Math]。

なメソッドをりたいは、のものをできます。

[System.Math] | Get-Member -Static -MemberType Methods

Mathクラスのいのをにします。

PS C:\> [System.Math]::Floor(9.42) 9 PS C:\> [System.Math]::Ceiling(9.42) 10

https://riptutorial.com/ja/home 183

Page 203: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS C:\> [System.Math]::Pow(4,3) 64 PS C:\> [System.Math]::Sqrt(49) 7

タイプの

アセンブリでライブラリを

Add-Type -AssemblyName "System.Math"

またはファイルパス

Add-Type -Path "D:\Libs\CustomMath.dll"

したタイプをするには

[CustomMath.NameSpace]::Method(param1, $variableParam, [int]castMeAsIntParam)

オンラインでのクラスのをむ https://riptutorial.com/ja/powershell/topic/1522/のクラスの

https://riptutorial.com/ja/home 184

Page 204: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

64: きロジックifexpression{}•ifexpression{} else {}•ifexpression{} elseifexpression{}•ifexpression{} elseifexpression{} else {}•

でできるもしてください。

Examples

if、else、else if

Powershellは、くのプログラミングにているなきをサポートしています。これにより、のでのやコマンドをすることができます。

するifブラケットコマンドは{}であればにのみされる()がたされ

$test = "test" if ($test -eq "test"){ Write-Host "if condition met" }

あなたはelseすることもできelse 。ここではelseはコマンドがされifのがたされていません 。

$test = "test" if ($test -eq "test2"){ Write-Host "if condition met" } else{ Write-Host "if condition not met" }

またはelseif 。 else ifは、 ifがたされず、 elseifがたされたifコマンドをします。

$test = "test" if ($test -eq "test2"){ Write-Host "if condition met" } elseif ($test -eq "test"){ Write-Host "ifelse condition met" }

の-eq のCmdLetとnot = or ==をすることにしてください。

ブールをすることができます。つまり、がではなくであるifステートメントをします。これは、してうことができます-Notコマンドレットを

https://riptutorial.com/ja/home 185

Page 205: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$test = "test" if (-Not $test -eq "test2"){ Write-Host "if condition not met" }

あなたもうことができます!

$test = "test" if (!($test -eq "test2")){ Write-Host "if condition not met" }

-ne しくないもあります。

$test = "test" if ($test -ne "test2"){ Write-Host "variable test is not equal to 'test2'" }

きの

をするは、のできロジックをすることができます。 'false'だけがtrue2.0とされます。

#Done in Powershell 2.0 $boolean = $false; $string = "false"; $emptyString = ""; If($boolean){ # this does not run because $boolean is false Write-Host "Shorthand If conditions can be nice, just make sure they are always boolean." } If($string){ # This does run because the string is non-zero length Write-Host "If the variable is not strictly null or Boolean false, it will evaluate to true as it is an object or string with length greater than 0." } If($emptyString){ # This does not run because the string is zero-length Write-Host "Checking empty strings can be useful as well." } If($null){ # This does not run because the condition is null Write-Host "Checking Nulls will not print this statement." }

オンラインできロジックをむ https://riptutorial.com/ja/powershell/topic/7208/きロジック

https://riptutorial.com/ja/home 186

Page 206: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

65:

'テキスト' - 'RegExPattern'と•

'text' -replace 'RegExPattern'、 'newvalue'•

[] ::マッチ "text"、 "pattern"マッチ•

[] :: "text"、 "pattern"の•

[regex] :: Replace "text"、 "pattern"、 "newvalue"•

[regex] :: Replace "text"、 "pattern"、{param$ m}#MatchEvaluator•

[regex] :: Escape "input"をエスケープする•

Examples

シングルマッチ

Regexをしてテキストにのパターンがまれているかどうかをくできます。 PowerShellでRegexをするにはのがあります。

#Sample text $text = @" This is (a) sample text, this is a (sample text) "@ #Sample pattern: Content wrapped in () $pattern = '\(.*?\)'

-Matchのみみの-matchesをしてがパターンとするかどうかをするには、 'input' -match 'pattern'というをします。これは、にじてtrueまたはfalseをしtrue 。したは、 $Matches -variableにアクセスして、とグループをできますパターンでされている。

> $text -match $pattern True > $Matches Name Value ---- ----- 0 (a)

また、 -matchをしてのをフィルタリングし、するのみをすこともできます。

> $textarray = @" This is (a) sample

https://riptutorial.com/ja/home 187

Page 207: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

text, this is a (sample text) "@ -split "`n" > $textarray -match $pattern This is (a) sample a (sample text)

2.0

のPowerShell 2.0では、をしてテキストをするためのしいコマンドレットがされました。をむtextinputごとにMatchInfoオブジェクトをします。するグループなどをつけるためにプロパティにアクセスできます。

> $m = Select-String -InputObject $text -Pattern $pattern > $m This is (a) sample text, this is a (sample text) > $m | Format-List * IgnoreCase : True LineNumber : 1 Line : This is (a) sample text, this is a (sample text) Filename : InputStream Path : InputStream Pattern : \(.*?\) Context : Matches : {(a)}

-matchとに、 Select-Stringはをにすことでのをフィルタリングするためにもできます。をむごとにMatchInfoオブジェクトをします。

> $textarray | Select-String -Pattern $pattern This is (a) sample a (sample text) #You can also access the matches, groups etc. > $textarray | Select-String -Pattern $pattern | fl * IgnoreCase : True LineNumber : 1 Line : This is (a) sample Filename : InputStream Path : InputStream

https://riptutorial.com/ja/home 188

Page 208: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Pattern : \(.*?\) Context : Matches : {(a)} IgnoreCase : True LineNumber : 3 Line : a (sample text) Filename : InputStream Path : InputStream Pattern : \(.*?\) Context : Matches : {(sample text)}

Select-Stringは、 -SimpleMatchスイッチをすることによって、のテキストパターンなしをしてすることもできます。

[RegEx] :: Matchをうまた、.NET [RegEx]クラスでななMatch()メソッドをすることもできます。

> [regex]::Match($text,$pattern) Groups : {(a)} Success : True Captures : {(a)} Index : 8 Length : 3 Value : (a) > [regex]::Match($text,$pattern) | Select-Object -ExpandProperty Value (a)

のなは、パターンにマッチするテキストをしいにきえることです。

#Sample text $text = @" This is (a) sample text, this is a (sample text) "@ #Sample pattern: Text wrapped in () $pattern = '\(.*?\)' #Replace matches with: $newvalue = 'test'

-ReplaceをするPowerShellの-replaceをすると、 'input' -replace 'pattern', 'newvalue'のをして、パターンにするテキストをしいにきえることができます。

https://riptutorial.com/ja/home 189

Page 209: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

> $text -replace $pattern, $newvalue This is test sample text, this is a test

[RegEx] :: ReplaceメソッドをするのReplace()は、 [RegEx] .NETクラスのReplace()メソッドをしてうこともできます。

[regex]::Replace($text, $pattern, 'test') This is test sample text, this is a test

MatchEvalutorをしてテキストをにきえます

パターンにするを、そののにづくしいにきえるがあり、しいをできなくなることがあります。このようなシナリオでは、 MatchEvaluatorがにです。

PowerShellでは、 MatchEvaluatorは、ののMatchオブジェクトをむのパラメータをつMatchEvaluator

とじくらいです。アクションのは、そののマッチのしいになります。 MatchEvalutorは[Regex]::Replace()メソッドでできます。

inside ()のテキストをさにきえる

#Sample text $text = @" This is (a) sample text, this is a (sample text) "@ #Sample pattern: Content wrapped in () $pattern = '(?<=\().*?(?=\))' $MatchEvalutor = { param($match) #Replace content with length of content $match.Value.Length }

> [regex]::Replace($text, $pattern, $MatchEvalutor) This is 1 sample text, this is a 11

sampleをにする

https://riptutorial.com/ja/home 190

Page 210: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

#Sample pattern: "Sample" $pattern = 'sample' $MatchEvalutor = { param($match) #Return match in upper-case $match.Value.ToUpper() }

> [regex]::Replace($text, $pattern, $MatchEvalutor) This is (a) SAMPLE text, this is a (SAMPLE text)

をエスケープする

パターンは、くのをしてパターンをします。。、 . 「の」をし、 +は「1つ」などをする。

これらのをするには、a . 、 +など、パターンで、あなたはなをするためにそれらをエスケープするがあります。これはでバックスラッシュ\であるエスケープをっています。 +をするには、 \+パターンをします。

のすべてのをえておくことはしいので、したいのすべてのをエスケープするには、 [RegEx]::Escape("input")メソッドをします。

> [regex]::Escape("(foo)") \(foo\) > [regex]::Escape("1+1.2=2.2") 1\+1\.2=2\.2

テキストのパターンのすべてのをつけるはあります。

#Sample text $text = @" This is (a) sample text, this is a (sample text) "@ #Sample pattern: Content wrapped in () $pattern = '\(.*?\)'

https://riptutorial.com/ja/home 191

Page 211: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

Select-String -AllMatchesスイッチをすることにより、すべてのグローバルをつけることができます。

> $m = Select-String -InputObject $text -Pattern $pattern -AllMatches > $m | Format-List * IgnoreCase : True LineNumber : 1 Line : This is (a) sample text, this is a (sample text) Filename : InputStream Path : InputStream Pattern : \(.*?\) Context : Matches : {(a), (sample text)} #List all matches > $m.Matches Groups : {(a)} Success : True Captures : {(a)} Index : 8 Length : 3 Value : (a) Groups : {(sample text)} Success : True Captures : {(sample text)} Index : 37 Length : 13 Value : (sample text) #Get matched text > $m.Matches | Select-Object -ExpandProperty Value (a) (sample text)

[RegEx] :: Matchesをう.NETの[regex]クラスのMatches()メソッドをして、のをグローバルにすることもできます。

> [regex]::Matches($text,$pattern) Groups : {(a)} Success : True Captures : {(a)} Index : 8 Length : 3 Value : (a) Groups : {(sample text)} Success : True Captures : {(sample text)}

https://riptutorial.com/ja/home 192

Page 213: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

66:

は、アクションをすです。これは、コンパイラ/インタプリタに、の、またはをし、をするようにする。 PowerShellはのでし、がににしてをするようにしますが、やそののデータにもします。なにえて、PowerShellには、やコードのをするのがあります-like、-match、-replaceなど。

Examples

1 + 2 # Addition 1 - 2 # Subtraction -1 # Set negative value 1 * 2 # Multiplication 1 / 2 # Division 1 % 2 # Modulus 100 -shl 2 # Bitwise Shift-left 100 -shr 1 # Bitwise Shift-right

-and # Logical and -or # Logical or -xor # Logical exclusive or -not # Logical not ! # Logical not

$var = 1 # Assignment. Sets the value of a variable to the specified value $var += 2 # Addition. Increases the value of a variable by the specified value $var -= 1 # Subtraction. Decreases the value of a variable by the specified value $var *= 2 # Multiplication. Multiplies the value of a variable by the specified value $var /= 2 # Division. Divides the value of a variable by the specified value $var %= 2 # Modulus. Divides the value of a variable by the specified value and then # assigns the remainder (modulus) to the variable

$var++ # Increases the value of a variable, assignable property, or array element by 1 $var-- # Decreases the value of a variable, assignable property, or array element by 1

PowerShellのは、にハイフン - と eqはequal 、 gt greater thanなどでされています。

オペレータのをするには、のにをけることができます。

i # Case-Insensitive Explicit (-ieq) c # Case-Sensitive Explicit (-ceq)

https://riptutorial.com/ja/home 194

Page 214: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

case-Insensitiveは、されていない "a" -eq "A"とじ "a" -eq "A"です。

2 -eq 2 # Equal to (==) 2 -ne 4 # Not equal to (!=) 5 -gt 2 # Greater-than (>) 5 -ge 5 # Greater-than or equal to (>=) 5 -lt 10 # Less-than (<) 5 -le 5 # Less-than or equal to (<=)

"MyString" -like "*String" # Match using the wildcard character (*) "MyString" -notlike "Other*" # Does not match using the wildcard character (*) "MyString" -match "$String^" # Matches a string using regular expressions "MyString" -notmatch "$Other^" # Does not match a string using regular expressions

コレクション

"abc", "def" -contains "def" # Returns true when the value (right) is present # in the array (left) "abc", "def" -notcontains "123" # Returns true when the value (right) is not present # in the array (left) "def" -in "abc", "def" # Returns true when the value (left) is present # in the array (right) "123" -notin "abc", "def" # Returns true when the value (left) is not present # in the array (right)

リダイレクション

したストリーム

cmdlet > file # Send success output to file, overwriting existing content cmdlet >> file # Send success output to file, appending to existing content cmdlet 1>&2 # Send success and error output to error stream

エラーストリーム

cmdlet 2> file # Send error output to file, overwriting existing content cmdlet 2>> file # Send error output to file, appending to existing content cmdlet 2>&1 # Send success and error output to success output stream

ストリームPowerShell 3.0

cmdlet 3> file # Send warning output to file, overwriting existing content cmdlet 3>> file # Send warning output to file, appending to existing content cmdlet 3>&1 # Send success and warning output to success output stream

VerboseストリームPowerShell 3.0

cmdlet 4> file # Send verbose output to file, overwriting existing content cmdlet 4>> file # Send verbose output to file, appending to existing content cmdlet 4>&1 # Send success and verbose output to success output stream

https://riptutorial.com/ja/home 195

Page 215: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

デバッグストリームPowerShell 3.0

cmdlet 5> file # Send debug output to file, overwriting existing content cmdlet 5>> file # Send debug output to file, appending to existing content cmdlet 5>&1 # Send success and debug output to success output stream

ストリームPowerShell 5.0

cmdlet 6> file # Send information output to file, overwriting existing content cmdlet 6>> file # Send information output to file, appending to existing content cmdlet 6>&1 # Send success and information output to success output stream

すべてのストリーム

cmdlet *> file # Send all output streams to file, overwriting existing content cmdlet *>> file # Send all output streams to file, appending to existing content cmdlet *>&1 # Send all output streams to success output stream

パイプ | とのい

リダイレクションは、ストリームをファイルまたはストリームからストリームにリダイレクトするだけです。パイプは、オブジェクトをパイプラインでコマンドレットまたはにポンピングします。パイプラインがどのようにするかは、リダイレクトがどのようにし、どのようにみれるかとはになります。PowerShellパイプラインの

オペランドタイプのミックスオペランドのタイプによってビヘイビアがまります。

"4" + 2 # Gives "42" 4 + "2" # Gives 6 1,2,3 + "Hello" # Gives 1,2,3,"Hello" "Hello" + 1,2,3 # Gives "Hello1 2 3"

"3" * 2 # Gives "33" 2 * "3" # Gives 6 1,2,3 * 2 # Gives 1,2,3,1,2,3 2 * 1,2,3 # Gives an error op_Multiply is missing

このは、にされたをもたらすがあります。

$a = Read-Host "Enter a number" Enter a number : 33 $a -gt 5 False

-replaceは、をしてのパターンをきえます。このは、2つのコンマでられたをします。パターンと

https://riptutorial.com/ja/home 196

Page 216: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

そのでデフォルトはのです。

"The rain in Seattle" -replace 'rain','hail' #Returns: The hail in Seattle "[email protected]" -replace '^[\w]+@(.+)', '$1' #Returns: contoso.com

-splitは、をサブのにします。

"A B C" -split " " #Returns an array string collection object containing A,B and C.

-joinは、のをのにします。

"E","F","G" -join ":" #Returns a single string: E:F:G

オンラインでをむ https://riptutorial.com/ja/powershell/topic/1071/

https://riptutorial.com/ja/home 197

Page 217: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

67:

Examples

Windowsは、EnvというPSドライブとしてされます。

すべてのをむリストをのようにできます。 Get-Childitem env

$ envによるのびし

$env:COMPUTERNAME

オンラインでをむ https://riptutorial.com/ja/powershell/topic/5635/

https://riptutorial.com/ja/home 198

Page 218: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

68: とのりい

Powershellでは、パスワードをでするのをけるため、さまざまなをし、なとしてします。キーまたはセキュアキーをしていない、これはじコンピュータのじユーザーがKeys / SecureKeysをしていないにのみされたをできるようになります。じユーザーアカウントでされるプロセスは、そのじマシンでそのされたをすることができます。

Examples

のをめるプロンプト

をするには、ほとんどの、 Get-Credentialコマンドレットをするがあります。

$credential = Get-Credential

あらかじめされたユーザー

$credential = Get-Credential -UserName 'myUser'

カスタムプロンプトメッセージをする

$credential = Get-Credential -Message 'Please enter your company email address and password.'

プレーンテキストパスワードへのアクセス

オブジェクトのパスワードはされた[SecureString]です。もなは、されたパスワードをしない[NetworkCredential]をすることです。

$credential = Get-Credential $plainPass = $credential.GetNetworkCredential().Password

ヘルパーメソッド .GetNetworkCredential() は、 [PSCredential]オブジェクトにのみします。 [SecureString]をするには、.NETメソッドをします。

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secStr) $plainPass = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

ストアドクレデンシャルの

されたをにしてするには、PowerShellのみみXMLシリアルClixmlをします。

https://riptutorial.com/ja/home 199

Page 219: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$credential = Get-Credential $credential | Export-CliXml -Path 'C:\My\Path\cred.xml'

インポートするには

$credential = Import-CliXml -Path 'C:\My\Path\cred.xml'

なことは、デフォルトではWindowsのデータAPIをし、パスワードをするためにされるキーは、コードがされているユーザーとマシンのにのことです。

その、されたは、のユーザーやのコンピュータのじユーザーによってインポートされません。

のなるユーザーとなるコンピューターでじののバージョンをすることにより、のユーザーがじシークレットをできるようになります。

ユーザーとコンピュータをファイルにれることで、されたすべてのを、じコードがハードコーディングなしでできるようにすることができます。

Encrypter

# run as each user, and on each computer $credential = Get-Credential $credential | Export-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

されたをするコード$credential = Import-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

のユーザーのファイルのしいバージョンがにロードされますまたは、ファイルがしないためにします。

されたフォームにをし、のときにパラメータとしてす

$username = "[email protected]" $pwdTxt = Get-Content "C:\temp\Stored_Password.txt" $securePwd = $pwdTxt | ConvertTo-SecureString $credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd # Now, $credObject is having the credentials stored and you can pass it wherever you want. ## Import Password with AES

https://riptutorial.com/ja/home 200

Page 220: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

$username = "[email protected]" $AESKey = Get-Content $AESKeyFilePath $pwdTxt = Get-Content $SecurePwdFilePath $securePwd = $pwdTxt | ConvertTo-SecureString -Key $AESKey $credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd # Now, $credObject is having the credentials stored with AES Key and you can pass it wherever you want.

オンラインでとのりいをむ https://riptutorial.com/ja/powershell/topic/2917/とのりい

https://riptutorial.com/ja/home 201

Page 221: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

69: スクリプトスクリプトにすると、スクリプトはPowerShellのすべてのエクスクルージョンポリシーにし、スクリプトのがされます。されたスクリプトは、されたにされた、にします。

スクリプトのには、コードがです。

なスクリプト/テストされませんさcertifiateまたはサードパーティからのまたは。•

でできるのまたは•とのできるの•

about_Signing @ TechNetのをむ

ポリシー

PowerShellには、スクリプトまたはをするためになをするなポリシーがあります。のスコープにしてポリシーをできます。コンピュータ、のユーザーおよびのプロセス。 ポリシーはにバイパスすることができ、ユーザーをするのではなく、ってポリシーにしないようにします。

なポリシーはのとおりです。

き スクリプトはされません

AllSigned すべてのスクリプトにするがあります

RemoteSigned すべてのローカルスクリプトがされます。されたリモートスクリプトのみ

はありません。すべてのスクリプトはされていますが、インターネットからダウンロードしたスクリプトをするにします

バイパス すべてのスクリプトがされ、はされません

のスコープののポリシーをします。ポリシーをします。すべてのポリシーがの、がされます。

powershell.exeプロセスをするときに、 Set-ExecutionPolicy cmdlet、Group Policyまたは-

ExecutionPolicyパラメーターをして、のポリシーをできます。

about_Execution_Policies @ TechNetでをむ

Examples

スクリプトにする

https://riptutorial.com/ja/home 202

Page 222: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

スクリプトにするには、 Set-AuthenticodeSignature -cmdletとコードをします。

#Get the first available personal code-signing certificate for the logged on user $cert = @(Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert)[0] #Sign script using certificate Set-AuthenticodeSignature -Certificate $cert -FilePath c:\MyScript.ps1

また、 .pfxファイルからをみることもできます。

$cert = Get-PfxCertificate -FilePath "C:\MyCodeSigningCert.pfx"

スクリプトは、がするまでです。にタイムスタンプサーバーをすると、のがれたでもスクリプトはなままです。また、のチェーンルートをむをすると、ほとんどのコンピュータがスクリプトのにしたをするのにちます。

Set-AuthenticodeSignature -Certificate $cert -FilePath c:\MyScript.ps1 -IncludeChain All -TimeStampServer "http://timestamp.verisign.com/scripts/timstamp.dll"

Verisign、Comodo、Thawteなどのできるプロバイダのタイムスタンプサーバーをすることをおめします。

Set-ExecutionPolicyをしたポリシーの

デフォルトスコープLocalMachineのポリシーをするには、のようにします。

Set-ExecutionPolicy AllSigned

のスコープのポリシーをするには、のコマンドをします。

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy AllSigned

-Forceスイッチをすると、プロンプトをにすることができます。

スクリプトのポリシーをバイパスする

くの、のポリシーにしていないのないスクリプトをするがあります。これをうなは、そのプロセスのポリシーをバイパスすることです。

powershell.exe -ExecutionPolicy Bypass -File C:\MyUnsignedScript.ps1

または、をすることもできます

powershell -ep Bypass C:\MyUnsignedScript.ps1

https://riptutorial.com/ja/home 203

Page 223: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

そののポリシー

ポリシー

AllSigned できるがしたスクリプトのみできます。

Bypass なし。すべてのWindows PowerShellスクリプトをできます。

Default はRemoteSigned 、ActiveDirectoryでされます

RemoteSigned ダウンロードしたスクリプトは、するにできるがするがあります。

Restrictedスクリプトはできません。 Windows PowerShellは、モードでのみできます。

Undefined NA

Unrestricted *

bypassと

Unrestricted*インターネットからダウンロードしたのないスクリプトをすると、にアクセスをめるプロンプトがされます。

はこちらからごください 。

のポリシーをする

のセッションのなポリシーをする

PS> Get-ExecutionPolicy RemoteSigned

のセッションのすべてのなポリシーをします。

PS> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser Undefined LocalMachine RemoteSigned

のスコープのポリシーをします。プロセス

https://riptutorial.com/ja/home 204

Page 224: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS> Get-ExecutionPolicy -Scope Process Undefined

されたスクリプトからをする

Get Get-AuthenticodeSignature -cmdletをして、きスクリプトからAuthenticodeにするをします。

Get-AuthenticodeSignature .\MyScript.ps1 | Format-List *

テストにりのコードをする

なスクリプトにするとき、またはコードをテストするときには、コードをするとです。

5.0

PowerShell 5.0から、 New-SelfSignedCertificate -cmdletをしてコードをすることができます。

New-SelfSignedCertificate -FriendlyName "StackOverflow Example Code Signing" -CertStoreLocation Cert:\CurrentUser\My -Subject "SO User" -Type CodeSigningCert

のバージョンでは、.NET Framework SDKおよびWindows SDKにあるmakecert.exeツールをしてをできます。

は、をインストールしたコンピュータによってのみされます。されるスクリプトの、できるまたはできるからのがされます。

オンラインでスクリプトをむ https://riptutorial.com/ja/powershell/topic/5670/スクリプト

https://riptutorial.com/ja/home 205

Page 225: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

70:

は、Windows PowerShellによっておよびされます。 1つは、ののどんなでもをびすことができます。これにするのは、PowerShellによってにされているです。これらのはいなく、のにあるPowerShellでもっともなオブジェクトです $はのの/のをします

$$ - セッションがにけったのトークンを$$ます。•

$^ - セッションでけったのののトークンをみます。•

$? - ののがまれます。•

$_ - のオブジェクトがパイプラインにまれています•

Examples

$ pid

のホスティングプロセスのプロセスIDがまれています。

PS C:\> $pid 26080

ブール

$trueと$falseはTRUEとFALSEをす2つのです。

のCとはなるとしてドルをするがあることにしてください。

$boolExpr = "abc".Length -eq 3 # length of "abc" is 3, hence $boolExpr will be True if($boolExpr -eq $true){ "Length is 3" } # result will be "Length is 3" $boolExpr -ne $true #result will be False

ブールtrue / falseをコードですると、 $trueまたは$falseとかれますが、PowershellがブールをすときはTrueまたはFalseようにえます

$ null

$nullは、またはのをすためにされます。 $nullはのののプレースホルダとしてできます

PS C:\> $array = 1, "string", $null

https://riptutorial.com/ja/home 206

Page 226: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS C:\> $array.Count 3

ForEach-Objectソースとしてじをすると、$ nullをむ3つのすべてがされます。

PS C:\> $array | ForEach-Object {"Hello"} Hello Hello Hello

してくださいこれがあることをForEach-Objectさえする $nullすべてで

PS C:\> $null | ForEach-Object {"Hello"} # THIS WILL DO ONE ITERATION !!! Hello

これはなforeachループとするとにしないになります

PS C:\> foreach($i in $null) {"Hello"} # THIS WILL DO NO ITERATION PS C:\>

$ OFS

フィールドセパレータとばれるには、をにするときにされるがまれています。デフォルトでは$OFS = " " スペース ですが、することができます

PS C:\> $array = 1,2,3 PS C:\> "$array" # default OFS will be used 1 2 3 PS C:\> $OFS = ",." # we change OFS to comma and dot PS C:\> "$array" 1,.2,.3

$ _ / $ PSItem

パイプラインによってされているオブジェクト/がまれます。

PS C:\> 1..5 | % { Write-Host "The current item is $_" } The current item is 1 The current item is 2 The current item is 3 The current item is 4 The current item is 5

$PSItemと$_はじ$PSItem 、じでできますが、 $_がこれまでにもにわれています。

$

ののステータスがまれます。エラーがない、 TrueされTrue 。

https://riptutorial.com/ja/home 207

Page 227: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PS C:\> Write-Host "Hello" Hello PS C:\> $? True

らかのエラーがあるは、 Falseされます。

PS C:\> wrt-host wrt-host : The term 'wrt-host' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + wrt-host + ~~~~~~~~ + CategoryInfo : ObjectNotFound: (wrt-host:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\> $? False

$エラー

のエラーオブジェクトの。アレイののものはのものです

PS C:\> throw "Error" # resulting output will be in red font Error At line:1 char:1 + throw "Error" + ~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (Error:String) [], RuntimeException + FullyQualifiedErrorId : Error PS C:\> $error[0] # resulting output will be normal string (not red ) Error At line:1 char:1 + throw "Error" + ~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (Error:String) [], RuntimeException + FullyQualifiedErrorId : Error

のヒントformatコマンドレットformat-listなどで$errorをするは、 -Forceスイッチをすることにしてください。それの、formatコマンドレットはので$errorをします。

エラーエントリは$Error.Remove($Error[0])でできます。

オンラインでをむ https://riptutorial.com/ja/powershell/topic/5353/

https://riptutorial.com/ja/home 208

Page 228: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

71: - パート2

トピック「」にはすでに7つのがリストされており、することはできません。このトピックでは、のきがあります。

は、PowerShellのをするです。これらのは、Windows PowerShellによっておよびされます。

これがのをするのであるかどうかはですが、これはもないよりれています。よりいをつけたらコメントしてください:)

Examples

$ PSVersionTable

のセッションでされているPowerShellのバージョンにするをするみりハッシュテーブルConstant

、AllScopeがまれています。

$PSVersionTable #this call results in this: Name Value ---- ----- PSVersion 5.0.10586.117 PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.10586.117 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1

PowerShellのバージョンをするの

$PSVersionTable.PSVersion # result : Major Minor Build Revision ----- ----- ----- -------- 5 0 10586 117

オンラインで - パート2をむ https://riptutorial.com/ja/powershell/topic/8639/---パート2

https://riptutorial.com/ja/home 209

Page 229: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

72: されたプロパティ

Powershellのされたプロパティは、カスタムプロパティです。これにより、ユーザーは、のプロパティをのでフォーマットすることができます。は、おそらくでもよい。

Examples

KBのファイルサイズの - されたプロパティ

のスニペットをえてみましょう。

Get-ChildItem -Path C:\MyFolder | Select-Object Name, CreationTime, Length

したプロパティでフォルダコンテンツをするだけです。かのようなもの、

ファイルサイズをKBでしたいのですがこれは、calcualtedプロパティがです。

Get-ChildItem C:\MyFolder | Select-Object Name, @{Name="Size_In_KB";Expression={$_.Length / 1Kb}}

それは、

Expressionは、されたプロパティのをするものです。はい、それはでもかまいません

オンラインでされたプロパティをむ https://riptutorial.com/ja/powershell/topic/8913/されたプロパティ

https://riptutorial.com/ja/home 210

Page 230: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

73: バーをする

プログレスバーをすると、かがプロセスにあることをすことができます。これは、をし、らかなです。プログレスバーは、デバッグにスクリプトのどのがされているかをするのににち、スクリプトをしている々ががこっているかをするのにしています。スクリプトのにがかかるは、らかのをするのがです。ユーザーがスクリプトをしてももこらない、スクリプトがしくしたかどうかにう。

Examples

プログレスバーのな

1..100 | ForEach-Object { Write-Progress -Activity "Copying files" -Status "$_ %" -Id 1 -PercentComplete $_ -CurrentOperation "Copying file file_name_$_.txt" Start-Sleep -Milliseconds 500 # sleep simulates working code, replace this line with your executive code (i.e. file copying) }

にするため、このにはコードはまれていません Start-Sleepシミュレートされています。しかし、それをし、それをしてすることはです。

これはPSコンソールでののです。

これはがPS ISEでどのようにえるかです

https://riptutorial.com/ja/home 211

Page 231: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

バーの

1..10 | foreach-object { $fileName = "file_name_$_.txt" Write-Progress -Activity "Copying files" -Status "$($_*10) %" -Id 1 -PercentComplete ($_*10) -CurrentOperation "Copying file $fileName" 1..100 | foreach-object { Write-Progress -Activity "Copying contents of the file $fileName" -Status "$_ %" -Id 2 -ParentId 1 -PercentComplete $_ -CurrentOperation "Copying $_. line" Start-Sleep -Milliseconds 20 # sleep simulates working code, replace this line with your executive code (i.e. file copying) } Start-Sleep -Milliseconds 500 # sleep simulates working code, replace this line with your executive code (i.e. file search) }

にするため、このにはコードはまれていません Start-Sleepシミュレートされています。しかし、それをし、それをしてすることはです。

これはPSコンソールでののです。

https://riptutorial.com/ja/home 212

Page 232: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

これはがPS ISEでどのようにえるかです

オンラインでバーをするをむ https://riptutorial.com/ja/powershell/topic/5020/バーをする

https://riptutorial.com/ja/home 213

Page 233: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

74: メールをする

Exchange Serverにとってなテクニックは、PowerShellからSMTPでメールメッセージをできることです。コンピュータまたはサーバーにインストールされているPowerShellのバージョンによっては、PowerShellでメールをするはあります。シンプルでいやすいネイティブのコマンドレットオプションがあります。コマンドレットSend-MailMessageをします 。

パラメーター

パラメータ

ファイル<String []>メッセージにするファイルのパスとファイル。パスとファイルはSend-MailMessageにパイプすることができます。

Bcc <String []>

メールメッセージのコピーをしたが、メッセージにとしてされないメールアドレス。[email protected]または[email protected]などのオプションとメールアドレスをします。

<String_> メールメッセージの。

BodyAsHtml これは、コンテンツがHTMLであることをします。

Cc <String []>メールメッセージのコピーをけるメールアドレス。[email protected]または[email protected]などのオプションとメールアドレスをします。

されたメールアドレスからメッセージをするをつユーザーアカウントをします。デフォルトはのユーザーです。 UserやDomain

\ Userなどのをするか、PSCredentialオブジェクトをします。

DeliveryNotificationOptionメールメッセージのオプションをします。のをできます。は、Toパラメータでされたアドレスにメッセージでされます。None

、OnSuccess、OnFailure、Delay、Never。

エンコーディングボディとのエンコーディングASCII、UTF8、UTF7、UTF32、Unicode、BigEndianUnicode、デフォルト、OEM。

からメールののメールアドレス。[email protected]または[email protected]などのオプションとメールアドレスをします。

https://riptutorial.com/ja/home 214

Page 234: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

パラメータ

SMTPサーバーのポート。は25です.Windows PowerShell 3.0からできます。

メールメッセージの。Normal、High、Low。

SmtpServerメールメッセージをするSMTPサーバーの。デフォルトは、$ PSEmailServerのです。

メールメッセージの。

にメールがされるメールアドレス。をしますオプション。メールアドレス。たとえば、は[email protected]または[email protected]です。

UseSslSSLSecure Sockets Layerプロトコルをしてリモートコンピュータとのをしてメールをする

Examples

なSend-MailMessage

Send-MailMessage -From [email protected] -Subject "Email Subject" -To [email protected] -SmtpServer smtp.com

みのパラメータをしたSend-MailMessage

$parameters = @{ From = '[email protected]' To = '[email protected]' Subject = 'Email Subject' Attachments = @('C:\files\samplefile1.txt','C:\files\samplefile2.txt') BCC = '[email protected]' Body = 'Email body' BodyAsHTML = $False CC = '[email protected]' Credential = Get-Credential DeliveryNotificationOption = 'onSuccess' Encoding = 'UTF8' Port = '25' Priority = 'High' SmtpServer = 'smtp.com' UseSSL = $True } # Notice: Splatting requires @ instead of $ in front of variable name Send-MailMessage @parameters

SMTPClient - メッセージに.txtファイルをむメール

https://riptutorial.com/ja/home 215

Page 235: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

# Define the txt which will be in the email body $Txt_File = "c:\file.txt" function Send_mail { #Define Email settings $EmailFrom = "[email protected]" $EmailTo = "[email protected]" $Txt_Body = Get-Content $Txt_File -RAW $Body = $Body_Custom + $Txt_Body $Subject = "Email Subject" $SMTPServer = "smtpserver.domain.com" $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) $SMTPClient.EnableSsl = $false $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body) } $Body_Custom = "This is what contain file.txt : " Send_mail

オンラインでメールをするをむ https://riptutorial.com/ja/powershell/topic/2040/メールをする

https://riptutorial.com/ja/home 216

Page 236: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

クレジット

S. No

Contributors

1 PowerShellをいめる

4444, autosvet, Brant Bobby, Chris N, Clijsters, Community, DarkLite1, DAXaholic, Eitan, FoxDeploy, Gordon Bell, Greg Bray, Ian Miller, It-Z, JNYRanger, Jonas, Luboš Turek, Mark Wragg, Mathieu Buisson, Mrk, Nacimota, oɔɯǝɹ, Poorkenny, Sam Martin, th1rdey3, TheIncorrigible1, Tim, tjrobinson, TravisEz13, vonPryz, Xalorous

2ActiveDirectoryモジュール

Lachie White

3Amazon WebサービスAWSSimple Storage ServiceS3

Trevor Sullivan

4Amazon WebサービスAWS

Trevor Sullivan

5 CSV Andrei Epure, Frode F.

6DSCクラスベースのリソースの

Trevor Sullivan

7 ISEモジュール Florian Meyer

8 MongoDB Thomas Gerot, Zteffer

9 Pesterの Frode F., Sam Martin

10PowerShell.exeコマンドライン

Frode F.

11 PowerShellクラスboeprox, Brant Bobby, Frode F., Jaqueline Vanek, Mert Gülsoy, Ranadip Dutta, xvorsx

12

Powershellスクリプトv2.0をってArtifactoryからのアーティファクトをダウンロードするには

ANIL

Powershellでテキス13 NooJ

https://riptutorial.com/ja/home 217

Page 237: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

トファイルのIPv4とv6をする

14 PowerShellとのTCP autosvet, RamenChef, Richard

15

PowerShellの "ストリーム"。デバッグ、、、エラー、、および

DarkLite1, Dave Anderson, megamorf

16 PowershellのGUI Sam Martin

17PowerShellのSQLクエリ

Venkatakrishnan

18PowerShellのバックグラウンドジョブ

Clijsters, mattnicola, Ranadip Dutta, Richard, TravisEz13

19PowerShellのパラメータ

Poorkenny

20 PowerShellのautosvet, Eris, Liam, Prageeth Saravanan, Ranadip Dutta, restless1987, Steve K

21 PowerShellのりBert Levrau, camilohe, Eris, jumbo, Ranadip Dutta, Thomas Gerot

22PowerShellパイプラインの

Alban, Atsch, Clijsters, Deptor, James Ruskin, Keith, oɔɯǝɹ, Sam Martin

23Powershellプロファイル

Frode F., Kolob Canyon

24Powershellモジュール

autosvet, Mike Shepard, TravisEz13, Trevor Sullivan

25 Powershellリモート Avshalom, megamorf, Moerwald, Sam Martin, ShaneC

26PowerShellワークフロー

Trevor Sullivan

27 PowerShellBert Levrau, Eris, James Ruskin, Luke Ryan, niksofteng, Ranadip Dutta, Richard, TessellatingHeckler, TravisEz13, Xalorous

28 Psake Roman

PSScriptAnalyzer - 29 Mark Wragg, mattnicola

https://riptutorial.com/ja/home 218

Page 238: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

PowerShellスクリプトアナライザ

30 RESTful APIとのautosvet, Clijsters, HAL9256, kdtong, RamenChef, Ranadip Dutta, Sam Martin, YChi Lu

31SharePointモジュール

Raziel

32 ShouldProcessの Brant Bobby, Charlie Joynt, Schwarzie2478

33URLエンコード/デコード

VertigoRay

34 WMIとCIM Frode F.

35 XMLファイルのautosvet, Frode F., Giorgio Gambino, Lieven Keersmaekers, RamenChef, Richard, Rowshi

36アーカイブモジュール

James Ruskin, RapidCoder

37インフラストラクチャの

Giulio Caccin, Ranadip Dutta

38 エイリアス jumbo

39 エラー Prageeth Saravanan

40 オブジェクトの Chris N, djwork, Mathieu Buisson, megamorf

41 コマンドレットのけ TravisEz13

42コメントベースのヘルプ

Christophe

43 スイッチ Anthony Neace, Frode F., jumbo, oɔɯǝɹ, Ranadip Dutta, TravisEz13

44 スクリプトのの autosvet, Frode F., jumbo, RamenChef

45スケジュールされたタスクモジュール

Sam Martin

46 スプラットautosvet, Frode F., Moerwald, Petru Zaharia, Poorkenny, RamenChef, Ranadip Dutta, TravisEz13, xXhRQ8sD2L7Z

47スペシャルオペレーター

TravisEz13

https://riptutorial.com/ja/home 219

Page 239: PowerShell - RIP Tutorial · 2019-01-18 · DSC 177 DSC 178 62: 179 179 179 Examples 179 179 179 179 179 180 Here-string 180 Here-string 180 ... Linux、およびOS Xであり、

48 セキュリティと YChi Lu

49 パッケージ TravisEz13

50 ハッシュテーブル Florian Meyer, Ranadip Dutta, TravisEz13

51 パラメータセット Bert Levrau, Poorkenny

52 ビルトイン Trevor Sullivan

53 ヘルプシステムの Frode F., Madniz, mattnicola, RamenChef

54マネージコードのめみC| VB

ajb101

55モジュール、スクリプト、

Frode F., Ranadip Dutta, Xalorous

56 ループ

Blockhead, Christopher G. Lewis, Clijsters, CmdrTchort, DAXaholic, Eris, Frode F., Gomibushi, Gordon Bell, Jay Bazuzi, Jon, jumbo, mákos, Poorkenny, Ranadip Dutta, Richard, Roman, SeeuD1, Shawn Esterman, StephenP, TessellatingHeckler, TheIncorrigible1, VertigoRay

57 パラメータ autosvet, jumbo, RamenChef

58 niksofteng

59 セット Euro Micelli, Ranadip Dutta, TravisEz13

60 ファイルの RamenChef, W1M0R

61 するの autosvet, CmdrTchort, Frode F., RamenChef

62 Frode F., restless1987, void

63 のクラスの Austin T French, briantist, motcke, Ranadip Dutta, Xenophane

64 きロジック Liam, lloyd, miken32, TravisEz13

65 Frode F.

66Anthony Neace, Bevo, Clijsters, Gordon Bell, JPBlanc, Mark Wragg, Ranadip Dutta

67 autosvet

68 とのりい 4444, briantist, Ranadip Dutta, TravisEz13

69 スクリプト AP., Frode F.

https://riptutorial.com/ja/home 220