所以,我对 PowerShell 相当陌生,只是不知道如何使用数组/列表/哈希表。我基本上想做Python描述的以下事情:
entries = {
'one' : {
'id': '1',
'text': 'ok'
},
'two' : {
'id': '2',
'text': 'no'
}
}
for entry in entries:
print(entries[entry]['id'])
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
但这在 PowerShell 中是如何工作的呢?我尝试过以下方法:
$entries = @{
one = @{
id = "1";
text = "ok"
};
two = @{
id = "2";
text = "no"
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道如何访问这些信息。
foreach ($entry in $entries) {
Write-Host $entries[$entry]['id']
}
Run Code Online (Sandbox Code Playgroud)
=> 错误
如何将此命令的输出重定向到变量?
Restore-ASDatabase -Server $Server -RestoreFile $File -Name $CINPUT -Security:$Choice -AllowOverwrite -ErrorAction Stop
Run Code Online (Sandbox Code Playgroud)
我试过这个:
Restore-ASDatabase -Server $Server -RestoreFile $File -Name $CINPUT -Security:$Choice -AllowOverwrite -ErrorAction Stop >$output
$output
Run Code Online (Sandbox Code Playgroud)
没有显示任何东西。命令iteslf确实输出了一些东西。但我想将此输出存储到变量中
数据库恢复操作成功完成。
(Get-ChildItem -File -Recurse -Path $path).Fullname 返回全名
(Get-ChildItem -File -Recurse -Path $path).Name 数组返回文件名数组但
(Get-ChildItem -File -Recurse -Path $path).Length只返回一个值 - 元素数
问题 - 如何将结果作为文件长度数组?
我不明白为什么我无法更改这些变量。如果我在调试模式下将它们输入控制台,它就会打印这些值。同样奇怪的是我如何能够更改第 24 行上的 allowedRequestors 变量,但不能更改其他任何变量。有谁知道为什么其他变量会发生这种情况?
$FilePath = "C:\Users\Desktop\TestScripts\testBulkAP.csv"
$headers = & $PSScriptRoot\GetToken.ps1
## preparing create Catalog data
$accesspacakgeRequest = '{"displayName":"","description":"sddsds","isHidden":false,"catalogId":"","accessPackageResourceRoleScopes":[],"accessPackageAssignmentPolicies":[{"displayName":"Initial Policy","description":"Initial Policy","durationInDays":365,"expirationDateTime":null,"canExtend":false,"requestApprovalSettings":null,"accessReviewSettings":null,"notificationSettings":null,"additionalInfo":null,"isDenyPolicy":false,"id":"","activeAssignmentCount":0,"accessPackageId":"00000000-0000-0000-0000-000000000000","accessPackageCatalog":null,"createdDateTime":null,"modifiedDateTime":null,"createdBy":"","modifiedBy":"","countOfUsersIncludedInPolicy":null,"requestorSettings":{"acceptRequests":true,"scopeType":"NoSubjects","allowedRequestors":[],"isOnBehalfAllowed":false},"questions":[]}]}'
$emlRequestUrl = "https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackages"
$accesspacakgeRequestObject = ConvertFrom-Json -InputObject $accesspacakgeRequest
$Content = Import-Csv $FilePath
foreach($assignmentData in $Content) {
$accesspacakgeRequestObject.catalogId = $assignmentData.catalogId
$accesspacakgeRequestObject.displayName = $assignmentData.displayName
$accesspacakgeRequestObject.description = $assignmentData.description
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestorSettings.scopeType = $assignmentData.scope
if ($assignmentData.scope -eq "SpecificDirectorySubjects") {
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestorSettings.allowedRequestors += New-Object -TypeName psobject -Property @{'@odata.type' = '#microsoft.graph.groupMembers'; 'id' = $assignmentData.groupId; 'description' = $assignmentData.groupName; 'isBackup' = 'false'}
}
$numApprovalStages = [int]$assignmentData.approvalStages
if ($numApprovalStages -gt …Run Code Online (Sandbox Code Playgroud) 我正在将应用程序从 C# 转换为 PowerShell。如何从 PowerShell 调用 LINQ?
[Data.DataTable]$dt = New-Object System.Data.DataTable
[Data.DataColumn]$column = New-Object System.Data.DataColumn "Id", ([int])
$dt.Columns.Add($column)
# add data
[Data.DataRow]$row = $dt.NewRow() #
$row["Id"] = 1
$dt.Rows.Add($row)
$row = $dt.NewRow() #
$row["Id"] = 2
$dt.Rows.Add($row)
# LINQ in C#: int[] results = dt.AsEnumerable().Select(d => d.Field("Id")).ToArray();
[int[]]$results = [Linq.Enumerable]::Select($dt,[Func[int,int]]{ $args[0]})
# Error: Cannot find an overload for "Select" and the argument count: "2"
Write-Host $results
Run Code Online (Sandbox Code Playgroud) 我有一组从某些注册表查询中检索到的路径。截至目前,它们仍然作为目录对象返回,但我需要将它们转换为字符串数组。在 PS 中执行此操作最有效的方法是什么?
代码:
$found_paths = @();
$uninstall_keys = getRegistrySubkeys "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" '\\Office[\d+.*]';
if ($uninstall_keys -ne $null)
{
foreach ($key in $uninstall_keys)
{
$product_name = getRegistryValue $key "DisplayName";
$version = getRegistryValue $key "DisplayVersion";
$base_install_path = getRegistryValue $key "InstallLocation";
$full_install_path = Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Office\d{1,2}\D?' | Select-Object FullName;
$found_paths += ,$full_install_path
}
}
write-output $found_paths;
Run Code Online (Sandbox Code Playgroud)
输出:
FullName
--------
C:\Program Files\Microsoft Office Servers\OFFICE15
C:\Program Files\Microsoft Office\Office15
Run Code Online (Sandbox Code Playgroud)
期望的输出:
C:\Program Files\Microsoft Office Servers\OFFICE15
C:\Program Files\Microsoft Office\Office15
Run Code Online (Sandbox Code Playgroud) 是否可以使用CMD和Powershell将2个文件合并为1个文件,如下所示:
file1-line1 tab file2-line1 file1-line2 tab file2-line2 file1-line3 tab file2-line3
所以它需要文件1第1行并插入一个选项卡,然后插入文件2第1行.然后对每个文件中的所有后续行执行此操作?
我正在编写一个遍历目录的递归函数,并复制其中的每个文件和文件夹.我在函数中的第一个检查是查看传入的路径是否有子节点.为了找到这个,我使用以下方法:
[array]$arrExclude = @("Extras")
Function USBCopy
{
Param ([string]$strPath, [string]$strDestinationPath)
try
{
$pathChildren = Get-ChildItem -Path $strPath
if($pathChildren.Length -gt 0)
{
foreach($child in $pathChildren)
{
if($arrExclude -notcontains $child)
{
$strPathChild = "$strPath\$child"
$strDestinationPathChild = "$strDestinationPath\$child"
Copy-Item $strPathChild -Destination $strDestinationPathChild
USBCopy $strPathChild $strDestinationPathChild
}
}
}
}
catch
{
Write-Error ("Error running USBCopy: " + $Error[0].Exception.Message)
}
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,我的函数可以工作,但我的代码会说当一个目录实际上有一个文件时它是空的.当我调试我的函数时,变量会说该文件夹有子项但变量的长度为0.任何人都知道如何解决这个问题?
我有一个CSV文件,它有两列Employee和Manager,我想将它们导入两个变量,以便稍后在我的脚本中使用.但是,当我运行我的代码时,它只捕获CSV中的最后一个数据项,因为前一个数据项被覆盖.
$CSVFiles = Import-CSV "C:\T2\EmployeeManager.csv"
ForEach($CSVFile in $CSVFiles)
{
$Employee = ($CSVFile.Employee); $Manager = ($CSVFile.Manager)
}
Run Code Online (Sandbox Code Playgroud) 在官方文档中提到这Length是 的一个别名Count,但是我发现它们的行为不同的一种情况。此外,如果我ForEach用 替换 method ForEach-Object,Length将会发出 3 。有人能解释一下吗?
> (1..3).ForEach({$_}).Length
1
1
1
Run Code Online (Sandbox Code Playgroud)
> (1..3).ForEach({$_}).Count
3
Run Code Online (Sandbox Code Playgroud) 我注意到,当ForEach在数组对象上运行并将输出捕获到新变量时,新变量不是 System.array 类型:
PS D:\Playground> $Arr = 1, 2, 3
PS D:\Playground> $Arr2 = $Arr.ForEach({$_})
PS D:\Playground> $Arr2.Gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Collection`1 System.Object
Run Code Online (Sandbox Code Playgroud)
相反,它是 类型Collection'1。
这是什么类型?它相当于数组吗?
顺便说一句,这与以下内容不同ForEach-Object:
PS D:\Playground> $Arr3 = $($Arr | ForEach-Object { $_ })
PS D:\Playground> $Arr3.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
Run Code Online (Sandbox Code Playgroud) 我是 Powershell 的新手,有人可以向我解释为什么括号和点用于:
(get-cluster).PreferredSite="SiteA"
Run Code Online (Sandbox Code Playgroud)
为什么不只是:
get-cluster | set-preferredSite -Name SiteA
Run Code Online (Sandbox Code Playgroud) 我有一个返回 DictionaryEntry 集合的脚本,我注意到如果该字典恰好只有一个 K/V 对,我必须指定 var.value 与如果它有多个 var.values !是什么赋予了?有没有通用的方法来解决这个问题?在一个命令中?
powershell ×13
arrays ×3
dictionary ×2
windows ×2
batch-file ×1
cmd ×1
enumeration ×1
hashtable ×1
import-csv ×1
json ×1
linq ×1
merge ×1
object ×1
psobject ×1
string ×1