PowerShell 오류 메시지에서 touch 명령으로 새 파일 만들기
데스크톱에 PowerShell을 사용하여 만든 디렉터리가 있는데, 지금은 그 디렉터리 안에 텍스트 파일을 만들려고 합니다.
디렉토리를 새 디렉토리로 변경하고 입력했습니다.touch textfile.txt.
다음과 같은 오류 메시지가 나타납니다.
touch : The term 'touch' 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
+ touch file.txt
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (touch:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException`
왜 안 되나요?항상 깃배시를 사용해야 하나요?
명령이 필요한 경우touchPowerShell에서 The Right Thing™을 수행하는 기능을 정의할 수 있습니다.
function touch {
Param(
[Parameter(Mandatory=$true)]
[string]$Path
)
if (Test-Path -LiteralPath $Path) {
(Get-Item -Path $Path).LastWriteTime = Get-Date
} else {
New-Item -Type File -Path $Path
}
}
이 기능을 프로필에 넣으면 PowerShell을 시작할 때마다 사용할 수 있습니다.
정의하기touch가명()으로New-Alias -Name touch -Value New-Item여기선 안 통할거에요New-Item필수 매개 변수가 있습니다.-TypePowerShell 별칭 정의에는 매개 변수를 포함할 수 없습니다.
Windows Powershell을 사용하는 경우 Mac/Unix의 터치에 해당하는 명령어는 다음과 같습니다.New-Item textfile.txt -type file.
파워셸에서 단일 파일을 생성하는 경우:ni textfile.txt
여러 파일을 동시에 만드는 경우:touch a.txt,b.html,x.jsis linux 명령어입니다.
ni a.txt,b.html,x.jswindow power shell 명령입니다.
에탄 레이스너가 지적했듯이,touch는 Windows나 PowerShell의 명령어가 아닙니다.
새 파일을 빨리 만들고 싶은 경우(기존 파일의 날짜만 업데이트하는 사용 사례에는 관심이 없는 것 같습니다) 다음을 사용할 수 있습니다.
$null > textfile.txt
$null | sc textfile.txt
첫번째 파일은 유니코드로 기본 설정되므로 파일이 비어있지 않고 유니코드 BOM인 2바이트가 포함됩니다.
두번째로 사용하는것은sc(의 별칭Set-Content파일 시스템에서 사용할 경우 시스템의 활성 ANSI 코드 페이지가 기본값으로 설정됩니다. 이 페이지는 BOM을 사용하지 않으므로 실제로 빈 파일을 만듭니다.
빈 문자열을 사용하는 경우 (''아니면""아니면[String]::Empty) 대신에$null줄이 끊어지기도 하고요.
노드를 사용하는 경우 이 명령만 사용하면 터치가 설치됩니다.
npm install touch-cli -g
여기 있습니다.touch오류 처리가 개선된 메소드:
function touch
{
$file = $args[0]
if($file -eq $null) {
throw "No filename supplied"
}
if(Test-Path $file)
{
throw "file already exists"
}
else
{
# echo $null > $file
New-Item -ItemType File -Name ($file)
}
}
이 함수를 에 추가합니다.C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1(존재하지 않는 경우 이 파일을 만듭니다.)
다음과 같이 사용합니다.touch hey.js
cd를 파일을 생성할 경로에 넣고 입력합니다.
여기에 new-item -item type 파일 이름을 입력합니다.파일 형식
예
새 항목 - 항목 유형 파일 인덱스.js
Ansgar Weechers의 도움이 되는 답변을 일반화하여 다음을 지원합니다.
여러 파일을 입력으로, 개별 인수로 전달(
touch file1 file2, 유닉스와 마찬가지로touchutility) 배열 인수가 아닌 (touch file1, file2), 후자는 단일 파라미터에 여러 값을 전달하는 PowerShell-diomatic 방식입니다.와일드카드 패턴을 입력(기존 파일을 대상으로 마지막 쓰기 타임스탬프를 업데이트할 때만 의미 있음)합니다.
-Verbose어떤 행동을 수행하는지에 대한 피드백을 얻을 수 있습니다.
참고:
이 기능은 유닉스의 핵심 기능만 모방합니다.
touch유틸리티:- 기존 파일의 경우 마지막 쓰기 및 마지막 액세스 타임스탬프를 현재 시점으로 설정합니다.
- 존재하지 않는 파일은 컨텐츠 없이 생성되는 반면.
완벽한 ), (PowerShell-Diomatic) ,
Touch-File, 이 대답을 보십시오.을 사용하려면 하려면 PowerShell 4 합니다를 하기 때문에 4 이 필요합니다.
.ForEach()배열 방식(이전 버전에 쉽게 적용할 수 있음).
function touch {
<#
.SYNOPSIS
Emulates the Unix touch utility's core functionality.
#>
param(
[Parameter(Mandatory, ValueFromRemainingArguments)]
[string[]] $Path
)
# For all paths of / resolving to existing files, update the last-write timestamp to now.
if ($existingFiles = (Get-ChildItem -File $Path -ErrorAction SilentlyContinue -ErrorVariable errs)) {
Write-Verbose "Updating last-write and last-access timestamps to now: $existingFiles"
$now = Get-Date
$existingFiles.ForEach('LastWriteTime', $now)
$existingFiles.ForEach('LastAccessTime', $now)
}
# For all non-existing paths, create empty files.
if ($nonExistingPaths = $errs.TargetObject) {
Write-Verbose "Creatng empty file(s): $nonExistingPaths"
$null = New-Item $nonExistingPaths
}
}
의 .New-ItemName,ItemType,그리고.Path매개변수가 제게 효과가 있었습니다. 경우에는_netrc파일 용서:
New-Item -Name _netrc -ItemType File -Path $env:userprofile
참고문헌
파워쉘에 .txt 파일을 만드는 데만 사용하면 어떨까요?
New-Item .txt
자세한 내용은 이 웹사이트를 확인하세요.
기본적으로 존재하지 않는 폴더를 생성하도록 기능을 확장하는 것을 좋아합니다.옵션을 제공하는 전통적인 행동을 원한다면 좋습니다.
function touch {
param([string]$Name,
[switch]$Traditional)
if (-not $Traditional) {
$names = $Name.Replace("\", "/").Replace("//", "/") -split "/"
$nameNormalized = $names -join "/"
$nameNormalized = $nameNormalized.TrimEnd($names[$names.count - 1]).TrimEnd("/")
if (-not (Test-Path $nameNormalized) -and ($names.count -gt 1)) {
New-Item -Path $nameNormalized -ItemType Directory > $null
}
}
if (-not (Test-Path $Name)) {
New-Item -Path $Name -ItemType File >$null
}
else {
(Get-Item -Path $Name).LastWriteTime = Get-Date
}
}
용도:
# will make the folder if it doesn't exist
touch filepath\file.extension
# will throw exception if the folder doesn't exist
touch filepath\file.extension -Traditional
# both will make the file or update the LastWriteTime if the file already exists
Windows(윈도우)의 Power Shell(파워 셸)을 사용하는 경우, 터치 명령에 오류가 표시될 수 있습니다.용도:
New-Item* filename.filetype
아니면
ni* filename.filetype
예를 들어,
New-Item name.txt or ni name.txt
저 같은 경우에는.m just create a alias do command in myuser_profile.ps1' 입니다.
Set-Alias touch ni
이 하여 와 수 touch example.js anotherone.md another.tsx
Windows pwsh 프로필에 이 파일을 넣고 다시 로드합니다.
함수 터치($myNewFileName) {New-Item $myNewFileName-type file}
터치는 맥OS의 pwsh OOB에서 작동하는 것 같습니다.
언급URL : https://stackoverflow.com/questions/32448174/creating-new-file-with-touch-command-in-powershell-error-message
'source' 카테고리의 다른 글
| UNIX 휴대용 원자 작동 (0) | 2023.09.28 |
|---|---|
| 많은 하위 디렉터리를 별도의 새로운 Git 저장소로 분리 (0) | 2023.09.28 |
| jQuery UI 대화상자에서 첫번째 텍스트 상자에 포커스를 설정하지 못하도록 합니다. (0) | 2023.09.28 |
| 팬더를 코드에 적용하려면 언제 사용해야 합니까? (0) | 2023.09.28 |
| 우커머스에서 행당 상품 수 변경 (0) | 2023.09.28 |