$a = '1'
$b = 1
$a.GetType().Name
$b.GetType().Name
输出:
String
Int32
我如何转换$a
为Int32
?
我的意思是像$b = 1
以下不起作用:
$a.ToType(Int32)
$a.ToType('Int32')
$a = '1'
$b = 1
$a.GetType().Name
$b.GetType().Name
输出:
String
Int32
我如何转换$a
为Int32
?
我的意思是像$b = 1
以下不起作用:
$a.ToType(Int32)
$a.ToType('Int32')
不幸的是,滚动不顺畅、滚动不流畅这一无法解决的问题让我别无选择,只能放弃 Ubuntu 并回到 Windows。然而,我完全爱上了 Linux shell,因此安装了 WSL。
现在,有没有办法让 WSL 在 Powershell/命令提示符中默认打开?我想通过某个应用程序打开 wsl 并能够直接进入 Linux 会话。有没有办法做到这一点?
我的文件中有一个用户 ID 列表,如下所示:
0012345
0345678
我将文件加载到数组中
$ary_UserList = @(Get-Content $src_user_list)
然后我按如下方式处理 ID:
ForEach ($user in $ary_UserList){
$userName = (Get-ADUser -identity "$user").Name
$aryGroups = ((Get-ADUser -Filter {Name -like $userName} -properties memberof).memberof | Select-String -Pattern "MYGRP*")
$DataRow = New-Object System.Object #Create an object to hold the output fields
$DataRow | Add-Member -MemberType NoteProperty -Name "User" -Value $user
$DataRow | Add-Member -MemberType NoteProperty -Name "Name" -Value $userName
$DataRow | Add-Member -MemberType NoteProperty -Name "ADGroup" -Value $aryGroups
$ary_GroupList += $DataRow
$DataRow | Format-Table |Out-String -Width 256
}
$ary_GroupList | Export-CSV -LiteralPath $outGroupFile -NoTypeInformation -Encoding UTF8
在屏幕上从 $DataRow | Format-Table |Out-String -Width 256,我看到了。
User Name ADGroup
---- ---- -------
0012345 Marian Bernedelo {CN=MYGRP-Managers,OU=Group Objects,DC=corp,DC=Company,DC=com, CN=MYGRP-Associates,OU=Group Objects,DC=corp,DC=Company,DC=com}
User Name ADGroup
---- ---- -------
0345678 Fanny Carlsbad CN=MYGRP-Associates,OU=Group Objects,DC=corp,DC=Company,DC=com
但 CSV 输出如下所示:
"User","Name","ADGroup"
"0012345","Marian Bernedelo","System.Object[]"
"0345678","Fanny Carlsbad","CN=MYGRP-Associates,OU=Group Objects,DC=corp,DC=Company,DC=com"
当有多个组时,如何将这些组放入 CSV 输出中?
谢谢!!
我运行我的程序,我输入Ctrl+ C,显然我想停止该程序。
但powershell总是询问“你想停止该程序吗?(y/N)”。
我怎样才能禁用它?我只是希望程序停止而没有这个无用的提示。
编辑:更多细节
Ctrl我有一个 spring boot 应用程序,如果我使用 java -jar 运行并使用+停止它C,则没有提示。
如果我使用“mvn spring-boot:run”运行它,然后使用Ctrl+停止它C,我会收到提示。我不想要这个提示。
解决方案:替换mvn spring-boot:run
为echo y | mvn spring-boot:run
执行python(交互模式)时是否可以自动加载脚本?
我的意思是像PowerShell中的脚本一样$Profile
,当PowerShell执行时,脚本会自动加载。
Python 脚本示例:
# autorun.py
import os
def cls():
os.system("CLS")
def pause():
os.system("pause")
#input("Press Enter to continue...")
如何让python启动时自动加载脚本?
当我使用命令py
或Python
.
我正在尝试使用 PowerShell 进行压缩,但它并不排除 .zip 文件中列出的文件excluded_paths
。我想特别排除所有__pycache__
可以嵌套在 python 代码库的不同级别中的文件夹。目前,所有内容都被压缩,包括应该排除的文件和文件夹。
$excluded_paths = @(
"${parent_folder}/.vscode/*",
"${parent_folder}/.git/*",
"${parent_folder}/temp/*",
"${parent_folder}/resources/documentation/*",
"${parent_folder}/**/useful/*",
"${parent_folder}/scripts/*",
"${parent_folder}/*.template.*",
"${parent_folder}/*TODO.*",
"${parent_folder}/$(Get-Item -Path $MyInvocation.MyCommand.Path).Name"
)
$exclude_pycache = Get-ChildItem -Path $parent_folder -Recurse -Directory -Filter "__pycache__" | ForEach-Object { $_.FullName }
$excluded_paths += $exclude_pycache
Pause
$winrar_path = "C:\Program Files\WinRAR\WinRAR.exe"
#$exclusion_switches = $excluded_paths | ForEach-Object { "-x'$_'" }
#& $winrar_path a -r -ep1 $exclusion_switches "$output_zip" "${parent_folder}\*"
$exclusion_string = $excluded_paths -join ' '
& $winrar_path a -r -ep1 "-x$exclusion_string" "$output_zip" "${parent_folder}\*"
我试过这个:
$exclusion_switches = $excluded_paths | ForEach-Object { "-x'$_'" }
& $winrar_path a -r -ep1 $exclusion_switches "$output_zip" "${parent_folder}\*"
并尝试了这个:
$exclusion_string = $excluded_paths -join ' '
& $winrar_path a -r -ep1 "-x$exclusion_string" "$output_zip" "${parent_folder}\*"
即使是一个简单的例子:
& $winrar_path a -r -x__pycache__ "$output_zip" "${parent_folder}\*"
不起作用。它会压缩,但不会排除所有__pycache__
文件夹。
好的,我试过了
& $winrar_path a -r "-x*__pycache__*" "$output_zip" "${parent_folder}\*"
这有效,但WinRAR 文档没有提到引用它。
我究竟做错了什么?
我想替换文本Powershell Startup
和CMD StartUp
下面的内容
# PowerShell
PS C:\Users\Admin>
# CMD
C:\Users\Admin>
和
PS >
CMD >
就像Python Start Up
这样只显示
>>>
这可能吗?
我正在创建一个带有基本变量的脚本,以通过 PS7 在 AD 中创建用户,而不是远程处理到 AD 并手动创建。它会回答几个问题,然后我的脚本将在最后运行以创建 AD 用户。
当我不知道 while 循环时,这是非常原始的起始块
$NewPassword = (Read-Host -Prompt 'Please enter User New Password' -AsSecureString)
$NewPasswordMatch = (Read-Host -Prompt 'Please re-enter User New Password' -AsSecureString)
$newp1 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewPassword))
$newp2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewPasswordMatch))
if ($newp1 -CEQ $newp2) {
Write-Host "Passwords matched" -ForegroundColor Green
} else {
Write-Host "Passwords incorrect - please reset in AD once user is
created" -ForegroundColor Red
}
我已经掌握了基础知识的所有内容,但我在密码循环功能方面遇到了困难。我一度让它循环,但它不会写主机“密码不匹配,请重试”。我现在已经玩了很多次了,但无法恢复到原来的样子,所以寻求帮助,并希望我犯了一个愚蠢的错误,因为我对代码视而不见。
我对 PowerShell 非常陌生,除了在线网络研讨会和书籍之外,我是自学的,我理解 While 的前提,但不是 100% 理解其中的要点。该脚本是在创建 AD 帐户之前创建的,完整的脚本是在您到达最后一个问题后创建它。之后它将运行 new-aduser 等。
while( $true){
$NewPassword = (Read-Host -Prompt 'Please enter User New Password' -AsSecureString)
$NewPasswordMatch = (Read-Host -Prompt 'Please re-enter User New Password' -AsSecureString)
$newp1 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewPassword))
$newp2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewPasswordMatch))
try{
if ($newp1 -CEQ $newp2){
Write-Host "Password Accepted" -ForegroundColor Green
}
Break
}
catch{
Write-Host "Passwords do not match, please try again" -ForegroundColor Red
}
}
我想获取 PDF 并将每个页面提取为图像。我已经能够使用 ImageMagick 和 GhostScript 做到这一点,但结果质量非常差。我尝试了许多不同的输出选项,但没有任何运气。下面的脚本应该是相当不言自明的。它可以工作,但与打开 PDF 相比,图像质量确实令人失望。
# Extract each page from a PDF as a png using ImageMagick
# ImageMagick requires GhostScript for PDF manipulation so have to make sure that is installed
# Current install folder: C:\Program Files\ImageMagick-7.1.1-Q16-HDRI
# Chocolatey package does not inclued the 'identify.exe' command
# Path to the PDF file
$pdfFilePath = "C:\0\MyFile.pdf"
# Output directory for images
$outputDirectory = "C:\0"
# Image type to output to (tried jpg, png, tiff etc)
$imageExtension = "jpg"
# Check if running as Admin
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Host "Please run this script as an administrator."; exit }
# Check if Chocolatey is installed, if not, install it
if (!(Test-Path "$env:ProgramData\chocolatey")) { Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) }
# Check for magick.exe on path; if not installed, install ImageMagick
$imageMagickExePath = Get-ChildItem -Path "C:\Program Files\ImageMagick-*" -Filter "magick.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
if (!(Get-Command "magick.exe" -ea silent) -and ($null -eq $imageMagickExePath)) { Write-Host "ImageMagick not found. Installing..."; choco install imagemagick -y }
if ($null -eq $imageMagickExePath) { Write-Host "Error: magick.exe not found at $imageMagickExePath"; exit }
Write-Host "magick.exe found at '$imageMagickExePath'"
# Check for gswin64.exe on path; if not installed, install GhostScript
$gsExePath = Get-ChildItem -Path "C:\Program Files\gs\gs*\bin" -Filter "gswin64.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
if (!(Get-Command "gswin64.exe" -ea silent) -and ($null -eq $gsExePath)) { Write-Host "GhostScript not found. Installing..."; choco install ghostscript -y }
if ($null -eq $gsExePath) { Write-Host "Error: gswin64.exe not found, this is required by ImageMagick for PDF manipulation"; exit }
Write-Host "gswin64.exe found at '$gsExePath'"
# Add Ghostscript directory to the PATH temporarily so that ImageMagick can use it
$env:Path += ";$($gsExePath | Split-Path -Parent)"
# Create the output directory if it doesn't exist
if (-not (Test-Path $outputDirectory)) { New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null }
# Convert each page of the PDF to PNG
$imageNamePrefix = [System.IO.Path]::GetFileNameWithoutExtension($pdfFilePath)
$imageNamePrefix = $imageNamePrefix -replace '\s+', '_'
# Use ImageMagick's identify command to get the total number of pages in the PDF
$numberOfPages = (identify "$pdfFilePath" 2>$null | Measure-Object -Line).Lines
Write-Host "'$pdfFilePath' has $numberOfPages pages"
# Use ImageMagick's convert command to convert PDF
Start-Process $imageMagickExePath -ArgumentList "convert `"$pdfFilePath`" -density 600 -quality 100 -antialias -resize 300% `"$outputDirectory\$imageNamePrefix-%d.$imageExtension`"" -NoNewWindow -Wait
# Determine the maximum number of digits to normalise all page numbers to that length
$maxDigits = $numberOfPages.ToString().Length
# Normalize page numbers
for ($i = 0; $i -le $numberOfPages; $i++) {
$pageNumber = "{0:D$maxDigits}" -f $i
$oldFileName = Join-Path $outputDirectory "$imageNamePrefix-$i.$imageExtension"
$newFileName = Join-Path $outputDirectory "$imageNamePrefix-$pageNumber.$imageExtension"
if ((Test-Path $oldFileName) -and !(Test-Path $newFileName)) { Rename-Item -Path $oldFileName -NewName $newFileName }
}
# Remove the Ghostscript directory from the PATH
$env:Path = $env:Path -replace [regex]::Escape(";"+($gsExePath | Split-Path -Parent))
# command-line tools for manipulating PDFs:
# https://libgen.rs/search.php?req=pdf+hacks&lg_topic=libgen&open=0&view=simple&res=25&phrase=1&column=defs
# pdftk (PDF Toolkit): pdftk is a command-line tool for manipulating PDF files. It can merge, split, rotate, watermark, and decrypt PDF files.
# QPDF: QPDF is another command-line tool for structural, content-preserving transformation of PDF files. It's particularly useful for linearizing PDFs, decrypting, and compressing them.
# Poppler Utilities (pdftohtml, pdftotext, pdfimages): Poppler is a PDF rendering library and its utilities provide command-line tools for converting PDFs to various formats such as HTML, text, and images. pdftohtml converts PDF to HTML, pdftotext converts PDF to plain text, and pdfimages extracts images from PDFs.
# Ghostscript: Ghostscript is a suite of software based on an interpreter for Adobe Systems' PostScript and Portable Document Format (PDF) page description languages. It can be used for a wide variety of tasks including converting PDFs to various formats, merging PDFs, and more.
# MuPDF: MuPDF is a lightweight PDF, XPS, and E-book viewer. It also includes command-line tools for extracting text and images from PDFs.
# PDFMiner: PDFMiner is a tool for extracting information from PDF documents. It includes a command-line tool for extracting text, images, and other content from PDFs.
function main {
$options = @('option1', 'option2', 'option3')
CLS; $n = 1
$options | foreach { "[{0}] {1}" -f $n, $_; $n++ }
choice /c 123 /m "Choose:"
"opt$lastexitcode"
pause; main
}
function opt1 { "this is option one" }
function opt2 { "this is option two" }
function opt3 { "this is option three" }
main
如果可能的话,直接调用其他函数并输入名称函数而不使用if或switch语句?