首页 > 解决方案 > Powershell 创建文件夹名称

问题描述

所以,我正在尝试创建一个文件夹,在其中合并 2 个字符串并获取日期;像这样:

第2345章

我的代码:

Get-ChildItem 'C:\Scripts\MetadataExport' | New-Item -Name (Get-ChildItem 'C:\Scripts\MetadataExport' -Name).Split('-')[2] + '_XIPs' + "_$((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory -Force

但它给了我以下错误:

  New-Item : A positional parameter cannot be found that accepts argument '_XIPs'.
  At line:1 char:45
  + ... taExport' | New-Item -Name (Get-ChildItem 'C:\Scripts\MetadataExport' ...
  +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
  + FullyQualifiedErrorId :     PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

你能帮我弄清楚我做错了什么吗?

最好的

标签: powershell

解决方案


如果要根据管道中的每个输入对象动态计算参数值,则需要使用延迟绑定脚本块( { ... }),其中自动$_变量引用手头的输入对象:

Get-ChildItem C:\Scripts\MetadataExport | New-Item -Type Directory -Force -Name {
  $_.Name.Split('-')[2] + '_XIPs' + "_$((Get-Date).ToString('yyyy-MM-dd'))" 
} -WhatIf

注意:上面命令中的-WhatIf常用参数是预览操作。-WhatIf 一旦您确定该操作将执行您想要的操作,请删除。


推荐阅读