商店编号可以是1-4位数字。
关于设备的命名方式,商店#26的名称为0026,但我想让技术人员能够轻松键入26以得到相同的结果。
如何通过附加前导零将这个变量格式化为4位数字?
## Ask user for store number and affected AP number to query
$Global:Store = Read-Host "Store Number ";
$Global:apNumber= Read-Host "AP Number ";
## Clean up input for validity
IF($store.length -le 4) {
$store =
}
答案 0 :(得分:7)
您将使用-format
运算符:
'{0:d4}' -f $variable
https://ss64.com/ps/syntax-f-operator.html
如果您的变量是整数,则上述方法将起作用,否则,可以将其转换为整数:
'{0:d4}' -f [int]$variable
答案 1 :(得分:4)
只是为了避免浪费PetSerAl的有用帮助(应该在某个时候删除注释):
除了使用format operator(-f
)(我认为是首选方法)之外,还可以使用相应值提供的格式化方法。
如果该值是一个字符串(如您所愿),则可以用零填充:
'26'.PadLeft(4, '0')
如果该值为数字,则可以将其格式化为字符串:
(26).ToString('0000')
答案 2 :(得分:3)
padleft和tostring的Foreach版本。第一个中的0必须用引号引起来:
using System.Runtime.InteropServices;
// ...
private void CreateSendItem(Outlook.Application Application)
{
Outlook.MailItem mail = null;
Outlook.Recipients mailRecipients = null;
Outlook.Recipient mailRecipient = null;
try
{
mail = Application.CreateItem(Outlook.OlItemType.olMailItem)
as Outlook.MailItem;
mail.Subject = "A programatically generated e-mail";
mailRecipients = mail.Recipients;
mailRecipient = mailRecipients.Add("Eugene Astafiev");
mailRecipient.Resolve();
if (mailRecipient.Resolved)
{
mail.Send();
}
else
{
System.Windows.Forms.MessageBox.Show(
"There is no such record in your address book.");
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message,
"An exception is occured in the code of add-in.");
}
finally
{
if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient);
if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients);
if (mail != null) Marshal.ReleaseComObject(mail);
}
}
使用范围:
'4' | % padleft 4 '0'
0004
4 | % tostring 0000
0004
带有前缀:
1..10 | % tostring 0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
答案 3 :(得分:-1)
在此处添加其他答案,如果您希望使数据数组具有特定的前导零结构(或对数据进行任何其他更改),则可以这样做:
$old_array = (0..100)
$new_array = @()
$old_array | % { $new_array += "{0:d3}" -f $_}