I am having the below code to get the data from remote servers. thanks to #Santiago Squarzon
$serverlist = Get-Content -Path "C:\ServerList.txt"
# Collect results here
$result = Invoke-Command -ComputerName $serverlist -ScriptBlock {
$paths_list = $env:Path -Split [System.IO.Path]::PathSeparator
foreach($sys_Path in $paths_list)
{
$Permissions = (Get-Acl -Path $sys_Path).Access
foreach($acl in $Permissions)
{
if(-not $acl.IdentityReference)
{
continue
}
[pscustomobject]#{
ComputerName = $env:ComputerName
SystemFolderPath = $sys_Path
IdenityReference = $acl.IdentityReference.Value
FileSystemRights = $acl.FileSystemRights
}
}
}
} -HideComputerName
$result | Export-Csv -Path "C:\status_report.csv" -NoTypeInformation
But I am getting below error while executing it
Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [Get-Acl], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetAclCommand
+ PSComputerName
Please let me know on this.
Might adding the following check before $Permissions = (Get-Acl -Path $sys_Path).Access would resolve the issue:
if (($sys_Path -eq $null) -or ($sys_Path -eq '') ) {
continue
}
Related
sorry if it's a silly question. I'm trying to get the "EnableDCOM" Registry Key of all the machines on the domain and disable them. I'm kinda stuck with getting the status of the registry key.
Get-Adcomputer -Filter * | Get-itemProperty -path HKLM:\Software\Microsoft\OLE -name "EnableDCOM"
Here is the error:
Get-ItemProperty : Cannot process argument transformation on parameter 'Credential'. userName
At line:1 char:28
... -filter * | Get-ItemProperty -path HKLM:\Software\Microsoft\OLE -name ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidData: (CN=DAYGROUP-PCI...=daygroup,DC=ca:PSObject) [Get-ItemProperty], ParameterB
indingArgumentTransformationException
FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.GetItemPropertyComman
d
After trying to use the domain admin credential:
The provider does not support the use of credentials. Perform the operation again without specifying credentials.
At line:1 char:1
get-adcomputer -filter * | Get-ItemProperty -path HKLM:\Software\Micr ...
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
This code can help you. Don`t forget to specify different credential if needed.
$ADComputers = ( Get-ADComputer -Filter * ).Name
$ResultArray = #()
foreach ( $Computer in $ADComputers ){
#Maybe you need specify different credential -Credential $cred
$Value = Invoke-Command -ComputerName $Computer -ScriptBlock {
$Value = Get-ItemPropertyValue -path 'HKLM:\Software\Microsoft\OLE' -name 'EnableDCOM'
return $Value
}
$PSO = [PSCustomObject]#{
Computer = $Computer
Value = $Value
}
$ResultArray += $PSO
}
$ResultArray
I'm trying to access the service status of the remote server. i wrote this
$ServerList = get-content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList)
{
$Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -like "SQL Server (*"} | select Status | format-wide
if($st -eq "Running")
{
$SeverName
$Status
}
else
{
}
}
it is showing
$Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
in error. i don't know what i am missing. but when i run without if condition if shows proper output.
$ServerList = Get-Content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList)
{
$Status= #(
Get-Service -ComputerName $ServerName -DisplayName "SQL Server (*" |
Select-Object -ExpandProperty Status)
if ("Running" -in $Status)
{
[PSCustomObject]#{
Server = $ServerName
Status = $Status
}
}
else
{
}
}
Explanation:
Get-Service docs: -DisplayName
Specifies, as a string array, the display names of services to be retrieved. Wildcards are permitted (used instead of Where-Object as such filtering is always faster).
Array subexpression operator #( ). -
Returns the result of one or more statements as an array. The result is always an array of 0 or more objects (i.e. force Powershell to always return an array when a call returns only one object or even $null)
Used [PSCustomObject]#{} in output instead of a sequence of strings (learn advantages at Everything you wanted to know about PSCustomObject).
enter image description here
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$count
#$farm = Get-SPFarm
$siteList = Get-SPSite -Limit 1
$serviceContext = Get-SPServiceContext($siteList[0])
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($servicecontext)
$profiles = $profileManager.GetEnumerator()
foreach ($hi in $profiles) {
if([string]::IsNullOrEmpty($hi["AboutMe"].Value) -eq $false){
write-host "Acount Name:"$hi.AccountName"|AboutMe:"$hi["AboutMe"].Value
$count++
}
}
write-host $count
I keep getting errors with the foreachloop, the following error. When I type SP-Farm, I get everything back so it can't be an access issue?
UserProfileDBCache_WCFLogging :: ProfileDBCacheServiceClient.GetUserData threw exception: Access is denied.
At line:8 char:10
+ foreach ($hi in $profiles) {
+ ~~~
+ CategoryInfo : OperationStopped: (:) [], UserProfileApplicationNotAvailableException
+ FullyQualifiedErrorId : Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException
The following PowerShell for your reference.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$count
$siteList = Get-SPSite -Limit 1
$serviceContext = Get-SPServiceContext($siteList[0])
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext)
$profiles = $profileManager.GetEnumerator()
foreach ($profile in $profiles) {
if([string]::IsNullOrEmpty($profile["AboutMe"].Value) -eq $false){
write-host "Acount Name:"$profile.AccountName"|AboutMe:"$profile["AboutMe"].Value
$count++
}
}
write-host $count
I'm on a Windows server 2008 R2 and I need an extract of the local profile list, so I use Powershell to look into the registry and get what I want :
$path = 'Registry::HKey_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\*'
$items = Get-ItemProperty -path $path
Foreach ($item in $items) {
$objUser = New-Object
System.Security.Principal.SecurityIdentifier($item.PSChildName)
$objName = $objUser.Translate([System.Security.Principal.NTAccount])
$item.PSChildName = $objName.value
}
echo $items | Select-Object -Property PSChildName | Export-Csv
C:\scripts\PSScripts\UserProfile.csv -Encoding UTF8
It worked with another machine using Windows Server 2012 R2 but here I got a lot of errors, but always the same one :
Exception calling "Translate" with "1" argument(s): "Some or all
identity references could not be translated." At
C:\scripts\PSScripts\users_profile.ps1:5 char:34
+ $objName = $objUser.Translate <<<< ([System.Security.Principal.NTAccount])
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
The .csv file is created but with issues, like a profile shown more than one time, like this :
DOMAIN\User1
DOMAIN\User2
DOMAIN\User3
DOMAIN\User3
DOMAIN\User4
DOMAIN\User5
DOMAIN\User5
DOMAIN\User5
DOMAIN\User6
Is there a difference between WS2008 and WS2012 which can cause this problem? Or is it something else?
I'd suggest using WMI to be consistent across platforms plus some error handling:
$path = 'C:\scripts\PSScripts\UserProfile.csv'
Get-CimInstance -ClassName Win32_UserProfile -Filter Special=FALSE -PipelineVariable user |
ForEach-Object -Begin {$ErrorActionPreference = 'Stop'} {
try
{
$id = [System.Security.Principal.SecurityIdentifier]::new($user.SID)
$id.Translate([System.Security.Principal.NTAccount]).Value
}
catch
{
Write-Warning -Message "Failed to translate $($user.SID)! $PSItem"
}
} |
Select-Object -Property #{Label='PSChildName'; Expression={$PSItem}} |
Export-Csv -Path $path -Encoding ascii -NoTypeInformation
PSv2 solution:
Get-WmiObject -Class Win32_UserProfile -Filter Special=FALSE |
ForEach-Object -Begin {$ErrorActionPreference = 'Stop'} {
try
{
$sid = $_.SID
$id = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $sid
$id.Translate([System.Security.Principal.NTAccount]).Value
}
catch
{
Write-Host "Failed to translate $sid! $_" -ForegroundColor Red
}
} |
Select-Object -Property #{Label='PSChildName'; Expression={$_}} |
Export-Csv -Path $path -Encoding ascii -NoTypeInformation
I am trying to import a CSV containing information on a large amount of users and computers. I am using this CSV to build my Active Directory. I am trying to build the computers and am having an issue with the foreach loops and I believe I may be misunderstanding them. Here is the relevant section of my code:
$adusercsv = Import-CSV .\tst.csv
foreach ($_.computername in $adusercsv)
{
if ($_.city -eq "Vancouver")
{
New-ADComputer -Name $_.computername -Path OU=Computers,OU=Vancouver,DC=VANDC
}
if ($_.city -eq "Calgary")
{
New-ADComputer -Name $_.computername -Path OU=Computers,OU=Calgary,DC=InternalCAL
}
}
This code throws the syntax error:
At line:21 char:12
+ foreach ($_.computername in $adusercsv)
+ ~
Missing 'in' after variable in foreach loop.
At line:21 char:39
+ foreach ($_.computername in $adusercsv)
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingInInForeach
How do I read each line from the array?
First off, the $_ is the default variable representing the current object in the pipeline. You are trying to assign the current computer to the computername property of an undefined variable... try this instead
$OUs = #{
Vancouver = 'OU=Computers,OU=Vancouver,DC=VANDC'
Calgary = 'OU=Computers,OU=Calgary,DC=InternalCal'
}
$aduserscsv = Import-CSV .\tst.csv
foreach ($row in $aduserscsv) {
New-ADComputer -Name $row.Computername -path $OUs.($row.city)
}
This has no error checking in, which would be advisable, but it demonstrates how you use the foreach (){} loop and how you don't need to check the property of the city if your values are in your source data
$_ is used for the current value in the pipeline. In this case, you should not use it.
Try this out:
adusercsv = Import-CSV .\tst.csv
foreach ($computer in $adusercsv)
{
if ($computer.city -eq "Vancouver")
{
New-ADComputer -Name $computer.computername -Path OU=Computers,OU=Vancouver,DC=VANDC
}
if ($computer.city -eq "Calgary")
{
New-ADComputer -Name $computer.computername -Path OU=Computers,OU=Calgary,DC=InternalCAL
}
}
Have a look on this page for an example.
You can try like this :
$adusercsv = Import-CSV .\tst.csv
foreach ($pc in $adusercsv)
{
if ($pc.city -eq "Vancouver")
{
New-ADComputer -Name $pc.computername -Path OU=Computers,OU=Vancouver,DC=VANDC
}
if ($pc.city -eq "Calgary")
{
New-ADComputer -Name $pc.computername -Path OU=Computers,OU=Calgary,DC=InternalCAL
}
}