Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

How to modify group policy using powershell?

$
0
0

Hi,

I am trying to configure hash publication for branchcache and below are the steps.

Click Start, click Run, type mmc, and then press ENTER. The Microsoft Management Console (MMC) opens.

2.    In the MMC, on the File menu, click Add/Remove Snap-in. TheAdd or Remove Snap-ins dialog box opens.

3.    In Add or Remove Snap-ins, in Available snap-ins, double-clickGroup Policy Object Editor. The Group Policy Wizard opens with the Local Computer object selected. ClickFinish, and then click OK.

4.    In the Local Group Policy Editor MMC, expand the following path:Computer Configuration, Administrative Templates, Network, Lanman Server. Click Lanman Server.

5.    In the details pane, double-click Hash Publication for BranchCache. TheHash Publication for BranchCache dialog box opens.

6.    In the Hash Publication for BranchCache dialog box, clickEnabled.

7.    In Options, click Allow hash publication for all shared folder, and then clickAllow hash publication for all shared folder.

8. Click OK.

I think, group policy cmdlet can do this. But I am unabale to find the GUID and Key for the same. Can anyone help in doing above steps using powershell?

Also, please guide me on using powershell for managing/modifying the group policies.


Restore Old WMI Repository - Windows Server 2012r2

$
0
0

Hello,

In an effort to fix an issue with "Invalid Class" errors, I followed the instructions for rebuilding the WMI Repository on an RDS Deployment server (running RD Connection Broker, RD Session Host, RD Gateway, RD Web Access, roles)

While rebuilding the repository fixed my problem, it seems to have blown up the RDMS (Remote Desktop Management Service) which will not start now, and I am not even able to add the server back to the Server Managment Pool. 

I was not able to make a backup or snapshot of the server, so I really need to get this fixed now.

All I have is the old Repository directory to work with.

My questions are: 

1.) Can I restore the old Repository just from the data files?  No backup was made (as there was no mention that was even possible)  All I have are the INDEX.BTR/MAPPING1.MAP/MAPPING2.MAP/MAPPING3.MAP/OBJECTS.DATA files

Any help is greatly appreciated, thank you in advance!

Best Regards,

-sMh-


Problems with get-scheduledtask

$
0
0

I'm monitoring multiple 2012 R2 servers (all deployed roughly at the same time) task scheduler where I use get-scheduled task within Invoke-Command to pull information on specific tasks. On one server however I get errors for some reason.

The parameter is incorrect. +CategoryInfo : Invalid argument: (MSFT_ScheduledTask:Root/Microsoft/...T_ScheduledTask) [GetScheduledTask], CimException  +FullyQualifiedErrorId: HRESULT 0x80070057,GetScheduledTask

Any idea what would be causing this sort of behavior just on that one server where it works fine on all the others.


yaro

Remove-ADGroupMember where member is in parent domain and group is in child domain

$
0
0

I have a parent domain (sandbox.local) and a child domain (child.sandbox.local) and want the capability to add and remove sandbox\User to a (domain local) group in the child domain. 

I can add the user to the group:

$GroupDN = (Get-ADGroup $groupsam -server "child.sandbox.local").DistinguishedName
$UserDN = (Get-ADUser $sam -server "sandbox.local").DistinguishedName
Add-ADGroupMember -Identity GroupDN -Members UserDN

Problem: when I use any of the commands listed below, I get an object not found or referral was returned from the server error.

Remove-ADGroupMember -Identity GroupDN -Members UserDN -server "sandbox.local"
Remove-ADGroupMember -Identity GroupDN -Members UserDN -server "child.sandbox.local"

Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"
Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"

Suggestions?

Paul

<Specific error codes.>



Remove-ADGroupMember -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "sandbox.local"

Remove-ADGroupMember : A referral was returned from the server
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:10 char:21
+ Remove-ADGroupMember <<<<  -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "sandbox.local"
    + CategoryInfo          : ResourceUnavailable: (CN=TestGroup,OU...,DC=local:ADGroup) [Remove-ADGroupMember], ADReferralException
    + FullyQualifiedErrorId : A referral was returned from the server,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember



Remove-ADGroupMember -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "child.sandbox.local"

Remove-ADGroupMember : Cannot find an object with identity: 'CN=user,OU=pacific,OU=KrbUsers,DC=ad,DC=spawar,DC=local' under: 'DC=pac,DC=
ad,DC=spawar,DC=local'.
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:10 char:21
+ Remove-ADGroupMember <<<<  -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "child.sandbox.local"
    + CategoryInfo          : ObjectNotFound: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
 


Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"

Remove-ADPrincipalGroupMembership : A referral was returned from the server
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:11 char:34
+ Remove-ADPrincipalGroupMembership <<<<  -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"
    + CategoryInfo          : ResourceUnavailable: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADPrincipalGroupMembership], ADReferra
   lException
    + FullyQualifiedErrorId : A referral was returned from the server,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipalGroupMembers
   hip



Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"

Remove-ADPrincipalGroupMembership : Cannot find an object with identity: 'CN=user,OU=pacific,OU=KrbUsers,DC=ad,DC=spawar,DC=local' under
: 'DC=pac,DC=ad,DC=spawar,DC=local'.
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:11 char:34
+ Remove-ADPrincipalGroupMembership <<<<  -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"
    + CategoryInfo          : ObjectNotFound: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADPrincipalGroupMembership], ADIdentityNotF
   oundException
    + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipal
   GroupMembership
 
 

Powershell: Get-PhysicalDisk returns incorrect total capacity of Physical Disk

$
0
0

Hi Everyone,

I am trying to automate expansion of disk space for my file server (Windows Server 2012 R2) using PowerShell script. There are total 10 Physical Disks (1 locally attached and 9 from SAN)

In order to get the Total Capacity of Physical Disks, I am using a command "Get-PhysicalDisk"

However, the output of this command shows incorrect sizes for FEW of the Physical Disks.

For example, if the actual total capacity is 5.81 TB, the command output shows 5.66 TB, which is 150 GB less than actual. Due to this incorrect outputs, I am not able to achieve the further automation process.

Request someone to provide some clue on why PowerShell "Get-PhysicalDisk" gives incorrect values.

Thanks,
Amit Jogi

error using Get-GPRegistryValue

$
0
0

I am running a command as below:

Get-GPRegistryValue -Name "test" -key "HKEY_LOCAL_MACHINE"


However I am getting the error:

Get-GPRegistryValue : The argument value cannot be an empty string.
Parameter name: keyPath
At line:1 char:1
+ Get-GPRegistryValue -Name "test" -key "HKEY_LOCAL_MACHINE"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (Microsoft.Group...tryValueCommand:GetGPRegistryValueCommand) [Get-GPRegistryValue], ArgumentException
    + FullyQualifiedErrorId : UnableToRetrievePolicyRegistryItem,Microsoft.GroupPolicy.Commands.GetGPRegistryValueCommand

The test GPO has SMB Signing related group policy settings defined. However I get this error message and even I give the full

registry path as HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters, I still get an error.

What am I doing wrong here.

How to change Datatable Row's BackColor?

$
0
0

Now I changed to use DataTable to link DataGridView  and thought I could change the backcolor of each row. But not sure how do that. Please advise. Thanks.

$dt = New-Object System.Data.DataTable
$dt.Columns.AddRange(@('TIme','Name','Age','Gender'))
$dt.Rows.Add(@((Get-Date).ToString('HH:mm:ss'),'Kate',45,'F')) | Out-Null
$dt.Rows.Add(@((Get-Date).ToString('HH:mm:ss'),'John',35,'M')) | Out-Null
$dt.Rows.Add(@((Get-Date).ToString('HH:mm:ss'),'Bill',58,'M')) | Out-Null
$dt.Rows.Add(@((Get-Date).ToString('HH:mm:ss'),'Jane',54,'F')) | Out-Null
$dt.Rows.Add(@((Get-Date).ToString('HH:mm:ss'),'Bill',26,'M')) | Out-Null
$form = New-Object System.Windows.Forms.Form
$form.Size = '500,300'
$form.StartPosition = 'Manual'
#$DataGridView.Rows.Insert('',(Get-Date).ToString(0,'HH:mm:ss'),'Mary',41,'F')
#$DataGridView.Rows[0].DefaultCellStyle.Backcolor = '100,255,100'

$dataGridView= New-Object System.Windows.Forms.DataGridView
$dataGridView.Size = '455,280'
$dataGridView.DataSource = $dt
$dt.DefaultView.Sort = 'Name DESC,Age ASC'
$form.Controls.Add($DataGridView)
$form.ShowDialog()


Migrating a lot of vm's and need a quick powershell script to keep track of vm's progress

$
0
0

Excuse the easy question but I could use a hand putting this together.

 

This command gets me the percent complete of the vm migrations

 

This command gets me the names of the vm's being migrated.

 

  • Sorry can't show output of actual server names 

 

How can I combine the commands to get the vm and its percent complete?


Script to Check for existing user and if not, create new user

$
0
0

Hey,

I am new to Powershell and trying to create an algorithm that creates a new user but only after checking to see if the user exists.

I have looked around online at what others have done and have been playing around with my code, but I can't get the script to run correctly and create a new user.

This is what I have so far...

Any help would be appreciated
--------------------------
#Checking if user exists
Function Get-ADUser {
$Name = "$FirstName $LastName"

$User = Get-ADUser =LDAPFilter"(SAMAccountName=$Name)"
If ($User -eq $Null) {
    return $false
    }
Else {
    return $true
}

#Checking if user exists

Function NewADUser{

Import-Module ActiveDirectoty -ErrorAction SilentlyContinue

    New-ADUser `
    -Name "$FirstName $LastName" `
    -GiveName $FirstName `
    -Surname $LastName `
    -UserPrincipalName "$FirstName.$LastName" `
    -Path "OU=Office Administration_OU,OU=Departments,DC=EC_Bond,DC=com" `
    -AccountPAssword (Read-Host -AsSecureString "Enter Password") -Enabled $true
}

#Adding logic to script
cls
$ch = checkuserExists $NewUserFirstName $NewUserSurname

[string]$NewUserFirstName = Read-Host -Prompt 'Please enter FirstName'
[string]$NewUserSurname = Read-Host -Prompt 'Please enter Surname'

If ($ch) {
    Write-Host "The user you are trying to create already Exists"
    }
    Else {
        [string]$UserCreation = Read-Host -Prompt 'Would you like to create the user [Y] or [N]?'
        If ($UserCreation -eq "Y") {
            NewADUser $NewUserFirstName $NewUserSurname
        }
        Else {
            #Abort process
            Write-Host "Process Aborted"
        }
    }
}

"Invoke-WmiMethod" can be use "msiexec.exe" ?

$
0
0

Hi Friends,

I have one question for Invoke-WmiMethod, I use this to remote install msi file is ok.

But if add parameters , always install fail.

I use parameters (msiexec /i C:\OpenJDK8U-jdk_x86-32_windows_openj9_8u232b09_openj9-0.17.0.msi INSTALLLEVEL=2 /quiet ) to install my PC is ok

But add this parameters in my script always fail.

My Script :

###################

 

$MsiPackageFolderLocation = "\\test\javaJDK"

$MsiPackageFileName = "OpenJDK8U-jdk_x86-32_windows_openj9_8u232b09_openj9-0.17.0.msi"

$Workstation = "pc1643"

$WorkstationFolder = "c$\"

$argument = "msiexec.exe /i c:\$MsiPackageFileName INSTALLLEVEL=2 /quiet"

$TestPath = Test-Path -Path "\\$Workstation\$WorkstationFolder\"
If ($TestPath -eq $True)
{
$CopyMsiFile = Copy-Item -Path "$MsiPackageFolderLocation\$MsiPackageFileName" -Destination "\\$Workstation\$WorkstationFolder\$MsiPackageFileName" -ErrorAction SilentlyContinue
$TestFileCopy = Test-Path -Path "\\$Workstation\$WorkstationFolder\$MsiPackageFileName"

  If ($TestFileCopy -eq $True)
  {
  $Result = Invoke-WmiMethod -ComputerName $Workstation -Path Win32_Product -Name Install -ArgumentList @($True,$Null,$argument)

    If ($Result.ReturnValue -eq "0")
    {Write-Host "Installation Successful"}
    Else
    {Write-Host "Installation Unsuccessful-Error Code:$Result.ReturnValue"}
  }
  Else
  {Write-Host "Error:  There was an error copying the MSI file to the remote workstation."}
}
Else
{
Write-Host "Error:  Could not copy the MSI file to the remote workstation.  The remote workstation's destination folder could not be found."
}

###########################

If  change to  $Result = Invoke-WmiMethod -ComputerName $Workstation -Path Win32_Product -Name Install -ArgumentList @($True,$Null,c:\$MsiPackageFileName) is ok

but "c:\$MsiPackageFileName" change to "$argument" , always fail!

If I change to :

#######

$MsiPackageFileName = "OpenJDK8U-jdk_x86-32_windows_openj9_8u232b09_openj9-0.17.0.msi"

$argList='msiexec.exe /i c:\$MsiPackageFileName INSTALLLEVEL=2 /quiet'
$sb=[ScriptBlock]::Create("Start-Process `"C:\Temp\$process`" -ArgumentList $argList -verb runas -Wait")
Invoke-Command -ComputerName $computer -ScriptBlock $sb

########

Still fail...Could you help?


Hi I can't to find solution for solve this issue, I have Event 364 Source File: /Content/1B/DCD02B975BCC454188A2BB1F036E3E590C25641B.exe Destination File: D:\WSUS\WsusContent\1B\DCD02B975BCC454188A2BB1F036E3E590C25641B.exe But I don't know how to deline this KB Number..

PowerShell - Query Event log Remotly

$
0
0

Hi,

We have a basic script which query the event log in the DCs and in the local exchange server.

These are the commands:

1) Exchange

Get-EventLog -ComputerName Exchange_Server -LogName "MSExchange Management" -EntryType Information -InstanceId 1073741825 -After $BeginDate -Before $EndDate

2) DCs

Get-WinEvent -ComputerName DC_Sevrer -FilterHashtable @{LogName="security"; startTime=$BeginDate; id=4720}

When running the script manually - everything work as expected.

When I tried running the script as a scheduale task, with 'nt authority\system' user, the event log part is failing.

I tried setting the scheduale task with my account - if storing a password it is working, otherwise not.

So I opened PowerShell session with 'nt authority\system' and try run the commands manualy - im getting the following error:

get-WinEvent : Could not retrieve information about the Security log. Error: Attempted to perform an unauthorized operation 

(Get-EventLog is failing to with a similar error)

The goal is to run this script as scheduale task - 'nt authority\system' is the user that I use for such tasks, but I cant understand what is the issue...

The servers are 2012R2,2016 and 2019 Win Server.

Appriciate your assitance here.

Thanks.

Run Powershell Command as Administrator on Remote Computer

$
0
0

Hi,

Can someone please assist me in running powershell command as an administrator on remote computer. I am running below command on remote computer but its not providing the desired results. It does not throw any error or it achieves the desired result.

Invoke-Command -ComputerName $servername -scriptblock {control.exe "intl.cpl,,/f:`"c:\myregionalcfg.xml`""}

I am trying to change the system locale on windows 7 machine remotely.

c:\myregionalcfg.xml file is available on the remote computer.


unable to execute script

$
0
0

hi Guys,

trying to run a script to install MSI file on a several machines, but it seems like something is missing, but unfortunately even the power shell help isn't informative enough

this is the script:

     

$servers = get-content "c:\temp\servers.txt"
$source = "c:\install"
$dest - "c$"

$testPath = "c:\install\7z1805.msi"

foreach (server in $servers) {
    if (Test-Connection -Cn $computer -quiet) {
        Copy-Item $source -Destination \\$server\$dest -Recurse -Force

        if (Test-Path -Path $testPath) {
            Invoke-Command -ComputerName $server -ScriptBlock {powershell.exe c:\install\7z1805.msi /quiet /passive
            Write-Host -ForegroundColor Green "Installation completed successfully" on $server
        }

     } else {
        Write-Host -ForegroundColor Red "$server is not online, Installation failed"
     }

i added a screen shot of what i see when i hover with the mouse under the red underline.

i'll be very grateful for your help.

Merge adjacent columns in a csv file into a single column and cell..

$
0
0

Hi All,

I am trying to merge adjacent columns to one single column and one cell. (I want to create the History column- As shown in below screenshot)

Can anyone pls provide the powershell script for the same?

Thanks

Vishnu


Run Powershell Command as Administrator and accept UAC automatically

$
0
0

Hi,

Can someone please assist me on how to run powershell script as an administrator and accept the UAC automatically. I have managed to run the script as an administrator, however its prompting to accept UAC which I want my script to accept automatically.

Please suggest.


Sort array by group count

$
0
0

I have an array and need to sort rows by group count in c1 and value in c2 both in descending order.

for example below, after sort, there will be 5 'a's first, 3 'c's second and then 2 'b's. how it possible?

Before     After
c1  c2     c1   c2
---  ---   ---   ---
a    20     a    20
b    -2     a    16
a    14     a    14
a      8     a     8
c    23     a     2
c      1     c    23
c     12    c    12
a      2    c     1
b      4    b     4
a    16    b    -2


write-eventlog on remote computer

$
0
0

I am trying to write an event to an eventlog on a remote computer. If the user that log's in to the remote computer (using Enter-PSSession) is in the 'local administrators' group on the remote computer, I can write successfully to the remote eventlog.

If the user is not in the 'local administrators' group on the remote computer I get the message:
The registry key for the log "Application" for source "FTPS" could not be opened.

I have tried the following:
- changing permissions in the registry
- adding the user to all other 'local' users group except the administrators group
- enabling firewall rules "Remote Eventlog...."

I have also tried the following command:
write-eventlog -computername computername -logname logname -sourcesource
Again, this only works if the user that is connecting to the remote computer is an local administrator.

Can anybody help me with this problem?

Kind Regards,
 


copying file between remote machines

$
0
0

Hello

I need to copy install files from remote network mapped drive (source) to remote servers(target),install software on target servers and restart windows services that are running on those machines.I am having trouble with copying file.I tested the following script by replacing copy-item command with get-content.My credentials pass through just fine and gets me content but it has issue with copying files.

foreach ($Target in Get-Content -path "\\$source\servers.txt")
#{
$source = "//mapped drive/"
$target = "computer B"
$secpasswd = ConvertTo-SecureString $test_passwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($test_account, $secpasswd)
Invoke-Command -Computername $source -Credential $mycreds -scriptblock{
    Copy-Item -path "$source\scripts\.exe file"  -Destination "c:\$target\temp" -force        
    Invoke-Command -Computername $target -Credential $Using:mycreds -ScriptBlock {stop service -"abc"}  

Error connecting to HPRM from powershell

$
0
0

Hi There,

I am trying to download files from HP records manager using document id.

I have this working in a excel using macro. I am trying to develop powershell script so that I can automate this easily 

can some one help me troubleshoot the below issue.

is it because of any package required to import. if you have a working script please share there is no much help on google for this topic.

thank you.

kumar

----------------------------------------------

Add-Type-Path"C:\Program Files (x86)\Hewlett-Packard\HP Records Manager\HP.HPTRIM.SDK.dll"

$db=New-ObjectHP.HPTRIM.SDK.Database

$db.Dispose()

Results

New-Object : Exception calling ".ctor" with "0" argument(s): "The type initializer for 'HP.HPTRIM.SDK.trimPINVOKE' threw an exception."
At line:3 char:8
+     $db = New-Object HP.HPTRIM.SDK.Database
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
 
You cannot call a method on a null-valued expression.
At line:5 char:5
+     $db.Dispose()
+     ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Reading Property Name and Value from an XML file

$
0
0

Hello,

I am super tired as I have been working long hours and now I'm down to my last stretch. I can't see the screen anymore. :)

Need your expertise here.

I am trying to get a very simple PowerShell script to display the Property Name and the value from the XML file below.

    <Property Name="SharedComputerLicensing" Value="0" />

What I have...

<Configuration>

     <Add SourcePath="http://MO3CDN-Prod.delta.rl.delta.com:3650/pr/b8f9b850-328d-4355-9145-c59439a0c4cf" OfficeClientEdition="32" Channel="Targeted">
        <Product ID="O365ProPlusRetail">
            <Language ID="en-us" />
            <ExcludeApp ID="OneDrive" />
            <ExcludeApp ID="Groove" />
            <ExcludeApp ID="Teams" />

        </Product>


     </Add>

     <Updates UpdatePath="http://MO3CDN-Prod.delta.rl.delta.com:3650/pr/b8f9b850-328d-4355-9145-c59439a0c4cf" Channel="Targeted" Enabled="TRUE" />
     <Display Level="None" AcceptEULA="TRUE" />


     <Logging Level="Standard" Path="C:\esd\logs" />

     <Property Name="FORCEAPPSHUTDOWN" Value="TRUE" />


     <Property Name="SharedComputerLicensing" Value="0" />


     <Property Name="PinIconsToTaskbar" Value="TRUE" />


</Configuration>


GenXit
Viewing all 21975 articles
Browse latest View live