facebook twitter hatena line email

「Windows/powershell/基本」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(dir存在判定)
行9: 行9:
 
{
 
{
 
  Write-Output "OK"
 
  Write-Output "OK"
 +
}
 +
</pre>
 +
==比較==
 +
<pre>
 +
$num = 10
 +
if ($num -eq 10) {
 +
  Write-Output 'OK'
 +
} else {
 +
  Write-Output 'NG'
 
}
 
}
 
</pre>
 
</pre>
 +
 +
その他比較
 +
<pre>
 +
if ($num -ne 10) # 等しくない
 +
if ( $value -gt 5 ) # <
 +
if ( $value -lt 5 ) # >
 +
if ( ($age -gt 13) -and ($age -lt 55) ) # and条件
 +
if ( $age -le 13 -or $age -ge 55 )# and条件
 +
</pre>
 +
 +
参考:https://docs.microsoft.com/ja-jp/powershell/scripting/learn/deep-dives/everything-about-if?view=powershell-7.1
  
 
==dir存在判定==
 
==dir存在判定==

2021年8月19日 (木) 15:39時点における版

変数

$path = "hoge.txt"

判定

$condition = true
if ($condition)
{
 Write-Output "OK"
}

比較

$num = 10
if ($num -eq 10) {
  Write-Output 'OK'
} else {
  Write-Output 'NG'
}

その他比較

if ($num -ne 10) # 等しくない
if ( $value -gt 5 ) # <
if ( $value -lt 5 ) # >
if ( ($age -gt 13) -and ($age -lt 55) ) # and条件
if ( $age -le 13 -or $age -ge 55 )# and条件

参考:https://docs.microsoft.com/ja-jp/powershell/scripting/learn/deep-dives/everything-about-if?view=powershell-7.1

dir存在判定

if (Test-Path .git)
{
 Write-Output "exists"
}

.gitのdirがある

変数で定義したpathを使用

$path = "hoge.txt"
$data = Get-Content $path

テキスト文置換

aaaをcccへ置換

$data = Get-Content hoge.txt | % { $_ -replace "aaa", "ccc" }
$data | Out-File hoge.txt

参考:https://teratail.com/questions/290149

エスケープ文字対応

[]などは、\でエスケープする

$data = Get-Content hoge.txt | % { $_ -replace "aaa\[hoge\]", "ccc[piyo]" }

実行ファイルのdirpath

version3未満の場合

$ScriptDir = $MyInvocation.MyCommand.Path
echo $ScriptDir
C:\Users\hoge1\Desktop\hoge.ps1

version3以上の場合

$ScriptDir = $PSScriptRoot
echo $ScriptDir
C:\Users\hoge1\Desktop

参考:https://www.vwnet.jp/Windows/PowerShell/pwd.htm