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

Inserting servername from a get-content foreach loop

$
0
0

I have a list on servers on a file called Servers.txt

I am running the following powershell:

$insertSql = @'

Insert Into dbo.serverpatch ([Source],[Description],[HotFixID],[InstalledBy],[InstalledOn])
Values('{0}','{1}','{2}','{3}','{4}')'@

 Get-Content C:\Servers.txt | foreach{
    Get-wmiobject -class win32_quickfixengineering |
        ForEach-Object{           
         $query = $insertSql -f $_.Source,$_.Description,$_.HotFixId,$_.InstalledBy,$_.InstalledOn
            Invoke-Sqlcmd  -ServerInstance Server\Instance -Query $query -Database MyDB
         }
     }

This cycles through the servers in Servers.txt and inserts the update info into a SQL table. I need to include the server name as a column in the insert, but I cant seem to get it to work..

Thanks,

Mark


shares folder permissions

$
0
0

I'm using the following to get Share Permissions and NTFS Permissions on shared folders.  I would like to change both to get the share permissions and the ntfs permissions of the childitem of each of the shares.  Basically I want to go down one level.

SHARE PERMISSIONS

function Get-SharePermissions{  
[cmdletbinding(
    DefaultParameterSetName = 'computer',
    ConfirmImpact = 'low'
)]
    Param(
        [Parameter(
            Mandatory = $True,
            Position = 0,
            ParameterSetName = 'computer',
            ValueFromPipeline = $True)]
            [array]$computer                       
            )
Begin {                 
    #Process Share report
    $sharereport = @()
    }
Process {
    #Iterate through comptuers
    ForEach ($c in $computer) {
        Try {     
            Write-Verbose "Computer: $($c)"
            #Retrieve share information from comptuer
            $ShareSec = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -ComputerName $c -ea stop
            ForEach ($Shares in $sharesec) {
                Write-Verbose "Share: $($Shares.name)"
                    #Try to get the security descriptor
                    $SecurityDescriptor = $ShareS.GetSecurityDescriptor()
                    #Iterate through each descriptor
                    ForEach ($DACL in $SecurityDescriptor.Descriptor.DACL) {
                        $arrshare = New-Object PSObject
                        $arrshare | Add-Member NoteProperty Computer $c
                        $arrshare | Add-Member NoteProperty Name $Shares.Name
                        $arrshare | Add-Member NoteProperty ID $DACL.Trustee.Name
                        #Convert the current output into something more readable
                        Switch ($DACL.AccessMask) {
                            2032127 {$AccessMask = "FullControl"}
                            1179785 {$AccessMask = "Read"}
                            1180063 {$AccessMask = "Read, Write"}
                            1179817 {$AccessMask = "ReadAndExecute"}
                            -1610612736 {$AccessMask = "ReadAndExecuteExtended"}
                            1245631 {$AccessMask = "ReadAndExecute, Modify, Write"}
                            1180095 {$AccessMask = "ReadAndExecute, Write"}
                            268435456 {$AccessMask = "FullControl (Sub Only)"}
                            default {$AccessMask = $DACL.AccessMask}
                            }
                        $arrshare | Add-Member NoteProperty AccessMask $AccessMask
                        #Convert the current output into something more readable
                        Switch ($DACL.AceType) {
                            0 {$AceType = "Allow"}
                            1 {$AceType = "Deny"}
                            2 {$AceType = "Audit"}
                            }
                        $arrshare | Add-Member NoteProperty AceType $AceType
                        #Add to existing array
                        $sharereport += $arrshare
                        }
                    }
                }
            #Catch any errors                 
            Catch {
                $arrshare | Add-Member NoteProperty Computer $c
                $arrshare | Add-Member NoteProperty Name "NA"
                $arrshare | Add-Member NoteProperty ID "NA"  
                $arrshare | Add-Member NoteProperty AccessMask "NA"           
                }  
            Finally {
                #Add to existing array
                $sharereport += $arrshare
                }                                                   
            }  
        }                        
End {
    #Display report
    $Sharereport
    }
}

NTFS PERMISSIONS

$ntfs = foreach ($b in (Get-WmiObject Win32_Share | where-object {$_.type -eq 0 -or $_.type -eq 2147483648 -and $_.name -ne 'admin$' -and $_.name -ne 'R$'})){$b | get-acl -ea SilentlyContinue | select @{n='Share Name';e={$b.name}}, owner, @{e={$_.accesstostring};Label="Permissions"}}


SMaximus7

Passing parameters on PowerShell.exe command line not working with -File option

$
0
0

I saved this script as num.ps1:

param([int] $Num)
Write-Output $Num

Problem:

PS D:\> .\num.ps1 2MB
2097152

PS D:\> powershell.exe .\num.ps1 2MB
2097152

PS D:\> powershell.exe -File .\num.ps1 2MB
powershell.exe : D:\num.ps1 : Cannot process argument transformation on parameter 'Num'. Cannot convert value "2MB" to type "System.Int32".
Error: "Input string was
At line:1 char:1
+ powershell.exe -File .\num.ps1 2MB
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : NotSpecified: (D:\num.ps1 : Ca...put string was :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Same problem exists when launching PowerShell from cmd.exe.  Why does it fail on the last attempt?  More importantly, how can I make it work?


-Tony

Power Shell Script for converting classic pages to modern

$
0
0

Hi Community, 

We have more than 200 SharePoint sites and we cant to convert all the pages in every site to modern experience . We got a script from Microsoft site and it is working fine. But,the issue is we have to run it again and again for each sites. 

If we store all the site names url in an excel page , can a Powers Shell script read the site names one by one do the convertion ?

Below is the script we used . Any help is appreciated.  Thanks !!! 

https://docs.microsoft.com/en-us/sharepoint/dev/transform/modernize-userinterface-site-pages-powershell


Get user SID using ADSI

$
0
0

To get a users SID, I would normally do something like so:

Get-ADUser bob | Select-Object SID

Which will return something like so:

SID
---
S-1-5-21-36739156-0036912583-12345678-97625

How would I go about, just getting the SID but using ADSI, as I would need to run a script on machines that do not have AD cmdlets


If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

Conservative RSS Profile assigns 2 CPUs when 1 RSS Queue is chosen

$
0
0

Hi,

I'm trying to understand how RSS works and while experimenting, I found out that when Convervative RSS Profile is used with 1 RSS Queue, Indirection Table stay the same, with two processors. Is that correct behavior?

I'm asking, because when I choose other RSS Profile (for example Closest or ClosestStatic), number of the processors in IndirectionTable always match NumberOfReceiveQueues.

Is that mean that I have some bad version of Powershell/Windows/Drivers or is it correct??

Can anyone help with that?

I've used Set-NetAdapterRss cmdlet to set things up.

Name : test_port
InterfaceDescription : Intel(R) Ethernet Server Adapter I350-T4 #2
Enabled : True
NumberOfReceiveQueues : 1
Profile : Conservative
BaseProcessor: [Group:Number] : 0:0
MaxProcessor: [Group:Number] : 0:26
MaxProcessors : 14
RssProcessorArray: [Group:Number/NUMA Distance] : 0:0/0 0:2/0 0:4/0 0:6/0 0:8/0 0:10/0 0:12/0 0:14/0 0:16/0 0:18/0 0:20/0 0:22/0 0:24/0 0:26/0
IndirectionTable: [Group:Number] : 0:0 0:2 0:0 0:2 0:0 0:2 0:0 0:2
...

get-pnpdevice status info

$
0
0

I have an ethernet device that I see has an error status when I run get-pnpdevice. All well and good, but how do I get an actual explanation of what the error is? The documentation says that the underlying WMI object isWin32_PnPEntity, but trying to pipe it through

Select-Object -Property ErrorDescription

 just gets me empty results, so I have no further info to try to diagnose. Is there something else that can be done to get get-pnpdevice to cough up more info, or another cmdlet that will do it instead?

This is on a 2019 Hyper-V server install, so the # of tools I have available to investigate is pretty limited.

Edit actual Group Policy, not registry-based

$
0
0
Hi!
Yes, we have several cmdlets for managing GPO’s in AD. And something for managing actual policies based on registry settings. But what about not registry-based policies!? How to add and edit for example Computer Configuration > Preferences > Control Panel Settings > Local Users and Groups policy to GPO? When we have some … 200 computers and we need to have different details (based on computer names, for example) written into Control Panel Settings policy? … If You understand what I mean. Can this be done using PowerShell?
More thanks, Alar.

File comparison -gt result false/positive

$
0
0

Hope somebody can help me. 
I don't get it why this i happening.

I have a copy script to do a directoy sync.
There i have the following Line:

If ($MatchingSourceFile.LastWriteTime -gt $TargetFile.LastWriteTime)

Output of the variables is:

MatchingSourceFile.LastWritetime : 02/12/2020 21:05:14
TargetFile.LastWritetime : 02/12/2020 21:05:14

Why does the If result with True?!?!

List of corrupted files/folders which can't be copied over

$
0
0

We've a virtual windows file server and running chkdsk in read only is throwing errors :-

File record segment 92495D is an orphan
File record segment 92495F is an orphan

80733 large file records processed.

Errors found. CHKDSK cannot continue in read-only mode.

So I understand we've to run chkdsk /f to fix the errors at first & that may delete the corrupted files/folder which it cannot recover.
I'm also sure there are many corrupted files/folders on the disk as when trying to delete certain files/folders it throws an the file/folders is corrupted & doesn't let us delete the folder.

Now can anyone please help with a script to list down such folders/files ?
It could be a simple script just trying to copy paste the data recursively and if it's not able to do it, it should put down the file/folder name, path and the error message in excel while the one's it CAN copy paste it should just ignore them by putting a certain message for them along with file name, path & message without actually pasting the data at destination.

That's the catch I don't really want to paste the data anywhere just want the script to perform the verification coz It's 1 TB of data & I don't want to utilize another 1TB of disk.

Thanks in advance

Set-ADAccountPassword failing

$
0
0

Hi All

I've been trying to organise a password reset command using Powershell, but running into issues

The command I'm using is:

set-ADAccountPassword -Identity "922448" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Welcome1" -Force)


where 922448 is the sAMAccountName and Welcome1 is just a test password

I've been running into this error:

 

set-ADAccountPassword : A referral was returned from the server
At line:1 char:1
+ set-ADAccountPassword -Identity '922448' -Reset -NewPassword (ConvertTo-SecureSt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (922448:ADAccount) [Set-ADAccountPassword], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.SetADAccountPassword

Not sure what's going wrong, I've tried parsing it with and without the -Reset parameter, getting the Powershell cmdlet to prompt for the new password, but no luck, always seem to be getting the same error

What could I be doing wrong?

Thanks

Re-assign Scom agents to new Gateway server

$
0
0

We have 2 SCOM 1807 management servers, and 45 SCOM Gateway server installed at various customers.
At a few customers we will install a new windows 2016 Scom Gateway server, and the current Windows 2012 gateway server will temporarily function as the failover gateway server
I found a script from the famous Kevin.
https://kevinholman.com/2018/08/06/assigning-gateways-and-agents-to-management-servers-using-powershell/

I'm a powershell beginner, so with some help i tweaked the script for our situation.
I get a popup, and can select one or multiple agents to assign the primary and failover gateway server. Configured this already for a few customers

$oldGW = "GW01.domain.com"
$newGW = "GW02.domain.com"
# Get Management Server Object Examples
$Primary = Get-SCOMManagementServer | where {$_.Name -eq $newGW} 
$Failover = Get-SCOMManagementServer | where {$_.Name -eq $oldGW}
# Get all agents currently assigned to a Management Server or GW
#$Agents = Get-SCOMAgent -ManagementServer $Failover
$Agents = Get-SCOMAgent -ManagementServer $Failover | Out-GridView -Title "Select the SCOM agents you want to set the management server for." -PassThru

# Reassigning all agents in an array of agents
ForEach ($Agent in $Agents)
{
               [string]$AgentName = $Agent.DisplayName
               $PriBefore = $Agent.GetPrimaryManagementServer().DisplayName
               $FailBefore = $Agent.GetFailoverManagementServers().DisplayName
               If ($FailBefore) 
			   {
# We need to remove any failover settings for this agent in case we are setting a primary server already in the failover list
    Write-Host "Removing Failover...."
                              Set-SCOMParentManagementServer -Agent $Agent -FailoverServer $null
               }
               If ($FailBefore -ne $Failover) {
                              Set-SCOMParentManagementServer -Agent $Agent -PrimaryServer $Primary
                              Set-SCOMParentManagementServer -Agent $Agent -FailoverServer $Failover  
               }
}
Write-Host SCOM agents $Agents.DisplayName had their Primary Management set to $NewGW. -ForegroundColor Green

But now i need  to remove the failover gateway server from all clients.
The bold part is the only thing I changed in the script

If ($FailBefore -ne $Failover) {
                              Set-SCOMParentManagementServer -Agent $Agent -PrimaryServer $Primary
                              Set-SCOMParentManagementServer -Agent $Agent -FailoverServer $Null

But is doesn't work.. I don't get a popup, and failover server is still configured on the agents..

What am i doing wrong?

Thanks

select text after last "\"

$
0
0

Dick,
I have a variable loaded by .csv for simplicity I indicate

$path = "\\10.0.1.2\folder1\subfolder2\xyz\"

NB: i have "....xyz\"

i need to extract the text following the last "\" to get the variable

$folder = "xyz"

how can I proceed considering that the number of folders and subfolders is undefined?


Is the OutputType parameter meaningless?

$
0
0

I come from an object-oriented programming perspective, and one thing I cling to even in the fluid world of scripting is strong typing. That's part of what I dig about PowerShell--you can strongly type variables if you want to, or skip it if you don't.

I also try to be fastidous and thorough in declaring functions. I use param blocks instead of in-line parameters, and decorate the input variables with applicable attirbutes like Mandatory, Position, and ValueFromPipeline. For example:

function Format-ValueList()
{
    [CmdletBinding()][OutputType([string[]])] param(  [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)][AllowEmptyString()][Object[]]$InputObject,[Parameter(Mandatory=$false)][string]$Separator=",",[Parameter(Mandatory=$false)][string]$Delimiter="",[Parameter(Mandatory=$false)][int]$ItemsPerLine= 5  )# The function body...


I include the function-level attributes like CmdletBinding and OutputType because they are described in the PowerShell language specification. But honestly, they don't seem to doanything. Any function with a begin, process, and / or end block will function like a commandlet regardless of whether it has the CmdletBinding attribute, and adding the attribute to a function that has no begin, process, or end block will not cause an error.

And regarding the OutputType parameter, as I have flagged in the title of this post--it also seems to be ignored. For example, the following works just fine:

function Bait-AndSwitch {
    [CmdletBinding()][OutputType([System.Data.OleDb.OleDbConnection])]param([Parameter(Position=13)][string]$AString)return 1,2,3,"No OleDbConnection here",5
}

Bait-AndSwitch 14

 

So, are these attributes things that the PowerShell development team just never actually implemented, or what? I should note that some parameter-level attributes, such as ValueFromPipeline, Position, and Mandatory do work and are very helpful.


jmh

Import from csv failing

$
0
0

Hi to all, 

I am trying to run a simple import which is not working: 

I have created a csv file with one column and one string 

Setlocation
BLT

$SCCM = import-csv c:\blt.csv
$SCCM = ForeEach-object {
$setlocation = $_.setlocation
}

when i check the result of $Setlocation i get nothing. 

I need it to be BLT. 

What am i doing wrong?

Thank you

Amir


Get-DhcpServerv4ScopeStatistics query problem

$
0
0

Hello, I am trying to return the value of the 'Free' field from the 'Get-DhcpServerv4ScopeStatistics' command. 

My attempt is 'Get-DhcpServerv4ScopeStatistics -ScopeID 10.90.0.0 | Select Free'. However this only returns 5 blank lines instead of the expected value of the 'Free' column which is '8'.

Can someone please help ?

Thank you.

How to continue the script if an error occurs?

$
0
0

Hi!

I have a script that loops through a list of servers, collecting info about patching levels and then writing to a SQL database.

My problem is that often, a server will be unreachable (for a variety of reasons) and the script will just stop. Is there a way to get it to carry on, ignoreing the error?

Here is the section of my code:

Get-Content C:\temp\Servers.txt | foreach{

$thisServerName=$_

        Get-wmiobject -class win32_quickfixengineering  -computername $thisServerName |
        
        ForEach-Object{  
        #Insert Update info into SQL database         
         $query = $insertSql -f $thisServerName, $_.Source,$_.Description,$_.HotFixId,$_.InstalledBy,$_.InstalledOn
            Invoke-Sqlcmd  -ServerInstance <Instance> -Query $query -Database <DBName>
            write-output "Scanning " $thisServerName
            }
         }

PS Remoting Invoke-Command ResourceUnavailable Errors

$
0
0

Hi,

Within the domain, PS remoting is enabled and is working fine for non-administrative users. I can successfully login to other servers in the domain. But when I try to run some of the commands with Invoke-Command, scripts fail with the following error.

 

Cannot connect to CIM server. Access denied 
    + CategoryInfo          : ResourceUnavailable: (MSFT_NetAdapter:String) [Get-NetAdapter], CimJobException
    + FullyQualifiedErrorId : CimJob_BrokenCimSession,Get-NetAdapter
    + PSComputerName        : <HOSTNAME2>

Here is the full powershell script I am trying to run on <HOSTNAME1> with remote session on <HOSTNAME2>.

$password = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>",$password);
$targetServers=@("<HOSTNAME2>")
ForEach($server in $targetServers) {
  $session = New-PSSession $server -Credential $cred
  Invoke-Command -Session $session -ScriptBlock { Get-NetAdapter -Name *eth0* }
}

But the same command (Get-NetAdapter -Name *eth0*) works if I run it on local powershell on <HOSTNAME2>. So my user <USERNAME> has access to run this command.

Similarly if I just try to run the Invoke-Command with another ScriptBlock (e.g. just hostname command) it works. So only some of the commands don't work. Do we need to configure another setting to allow execution of specific commands with Invoke-Command ?

Here is the working version of this script with "hostname" ScriptBlock.

$password = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>",$password);
$targetServers=@("<HOSTNAME2>")
ForEach($server in $targetServers) {
  $session = New-PSSession $server -Credential $cred
  Invoke-Command -Session $session -ScriptBlock { hostname }
}

Thank you.

read file into variable

$
0
0

i am using ps v1.0 (at a client site) i need to read a html file into a variable 

Get-Content "File Name" | Out-String

how do i convert Out-String to  a variable that i can use?

thx 4 ur help 


y zidell

Missing argument in parameter list

$
0
0

I have created a directory:

skeleton /
NAME/
_ _ i n i t _ _ . py
bin /
docs /
setup . py
t e s t s /
NAME_tests . py
_ _ i n i t _ _ . py

2. After that, I have to create two initial files:


new -item -type f i l e NAME/ _ _ i n i t _ _ . py
new -item -type f i l e t e s t s / _ _ i n i t _ _ . py

I am supposed to execute nosetests and get something like:

Ran 0  t e s t s  i n  0.000 s

If something goes wrong I am supposed to type:

NAME,bin,docs,setup.py,tests (no spaces)

It is here where I get the following error: missing argument in parameter list.



Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>