facebook twitter hatena line email

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

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(指定文字の行数を置換)
(指定文字の行数を置換)
行126: 行126:
 
$num = Select-String siro ./user.txt | ForEach-Object { $($_ -split":")[1]}
 
$num = Select-String siro ./user.txt | ForEach-Object { $($_ -split":")[1]}
 
if ($num) {
 
if ($num) {
     $data = Get-Content ./user.txt
+
     $lines = Get-Content ./user.txt
     $data[$num - 1] = "nanaro"
+
     $lines[$num - 1] = "nanaro"
     $data | Out-File ./user.txt
+
     $lines | Out-File ./user.txt
 
}
 
}
 
</pre>
 
</pre>

2021年8月27日 (金) 22:04時点における版

変数

$hoge = "hogehoge"

判定

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

比較

$num = 10
if ($num -eq 10) {
  Write-Host 'OK'
} else {
  Write-Host '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

文字列内に変数

echo "hoge=$hoge"
echo "hoge=${hoge}"
echo ('hoge=' + $hoge)

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

dir存在判定

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

.gitのdirがある

↓存在しないときの判定

if (!(Test-Path .git))

変数で定義したpathを使用

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

テキスト置換

$name = $name.Replace('taro', 'jiro')

ファイル内のテキスト文置換

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
(windowsの場合) C:\Users\hoge1\Desktop\hoge.ps1
(macの場合) /System/Volumes/Data/www/PowerShells/hoge.ps1

version3以上の場合

$ScriptDir = $PSScriptRoot
echo $ScriptDir
(windowsの場合) C:\Users\hoge1\Desktop
(macの場合) /System/Volumes/Data/www/PowerShells

macで使おうとしたが、初回は使えなかった。数日置いて確認した所使えたので、再起動などが、要因かもしれない。

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

ログ

function log($msg) {
  echo ($(Get-Date -Format "yyyy-MM-dd HH:mm:ss ") + $msg)
}
log "hogehogeを処理中です"
> 2021-03-20 22:27:18 hogehogeを処理中です

コマンドの戻り値を取得

変数にそのまま入れれば良い。

$proc = az storage blob sync

指定文字のある行数を取得

user.txt

taro 14
jiro 12
saburo 10
siro 8
goro

serachfile.ps1

$num = Select-String siro ./user.txt | ForEach-Object { $($_ -split":")[1]}

4

x行目を削除

$data = Get-Content ./user.txt
$data[3] = $null
$data | Out-File ./user2.csv

3と書けば、4行目が対象となる

指定文字の行数を置換

$num = Select-String siro ./user.txt | ForEach-Object { $($_ -split":")[1]}
if ($num) {
    $lines = Get-Content ./user.txt
    $lines[$num - 1] = "nanaro"
    $lines | Out-File ./user.txt
}