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

HELP!!! How to do a WMI SUPERCLASS reference using POWERSHELL

$
0
0

Hi friends,

I'm developing a WMI subclass and I would like to reference a superclass to my subclass.

I know the MOF code is:

class MySubClass : __Superclass

How can I do the same using Powershell?

My PS code is:

$NewClass = New-Object System.Management.ManagementClass ("root\MySubClass", "root\MySubClass\__Superclass", $null);
$NewClass['__CLASS'] = "MySubClass"
$NewClass.Properties.Add('Name', [System.Management.CimType]::String, $false)
$NewClass.Properties['Name'].Qualifiers.Add('Key', $true)

Thanks

Tavares



Invoke-WebRequest to use data to generate a report of broken links on a webpage.

$
0
0

I am a student at a community college seeking an Associate in Applied Computer Sciences, Web/database Development.  I am due to graduate this coming spring of 2017. I am presently learning how to use MS PowerShell.  For my end of term final project I have decided to write a utility in PowerShell that will check a web page, and return a report of broken links.  Present I am stalled with the code and can not figure out what to do next.  Would like some help here or some suggestions.    My presentation is due by 1 pm Monday November 28th.  I am in a panic mode.  Thanks!

Here is what I have so far...

#####Infomation

#PSVersion                      5.1.14393.206                                                                              
#PSEdition                      Desktop                                                                                    
#PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                    
#BuildVersion                   10.0.14393.206                                                                             
#CLRVersion                     4.0.30319.42000                                                                            
#WSManStackVersion              3.0                                                                                        
#PSRemotingProtocolVersion      2.3                                                                                        
#SerializationVersion           1.1.0.1                   

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

Clear-Host

##Two hash marks for Notes:

##Creating Varible $Results which is  an array of objects, all href links
#Results = (Invoke-WebRequest -Uri '<url to page being checked').Links | Select href
$Results = (Invoke-WebRequest -Uri 'http://vetshelpingvetshq.com').Links | Select href
###$Results.GetType()

##Creates a text file of $Results which contains inner and outer href links
##So I could use Select-Object Line to narrow the list to outgoing urls
$Results | Out-File -filepath C:\Users\Derral\Documents\Results\UrlList.txt

##Another array of object which narrows down the list to outbound urls http:
$OutLinks = Select-String C:\Users\Derral\Documents\Results\UrlList.txt -pattern "http" | Select-Object Line
#$OutLinks.GetType()
#OutLinks

##From here I desired to use a for loop to iterate all values in the array and checking each link and using
##the StatisCode or StatusDescription to output a text file which will be a list of broken links on the webpage.


##Error messages for every link that is checked...
#for($i=0; $i -le $Outlinks.length - 1; $i++) {(Invoke-WebRequest - Uri '$OutLinks[$i]').StatusDescription}


##A simple check of one url in the array me an error message.
##I am stuck here and can not see what I am doing wrong.
(Invoke-WebRequest - Uri '$OutLinks[8]').StatusDescription##Invoke-WebRequest : A positional parameter cannot be found that accepts argument 'Uri'.

##At line:37 char:2
##+ (Invoke-WebRequest - Uri '$OutLinks[8]').StatusDescription
##+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
##    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
##



##It is obvious that I am a beginner in PowerShell but I recognize the fact that this is a powerful programming
##language that can be used to write many utilities that will aid in maintenance tasks in a developed website.


##From here there are so many options. Auto email to web admin.  A webpage in the admin section of the site containing
##various quality control reports.

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

Clear-Host

$Results = (Invoke-WebRequest -Uri 'http://google.com').Links | Select href

$Results | Out-File -filepath C:\Users\Derral\Documents\Results\UrlList.txt

$OutLinks = Select-String C:\Users\Derral\Documents\Results\UrlList.txt -pattern "http" | Select-Object Line

for($i=0; $i -le $Outlinks.length - 1; $i++) {(Invoke-WebRequest - Uri '$OutLinks[$i]').StatusDescription}

###This is where the errors occur plugging in the urls from the text file into Invoke-WebRequest.

###I am thinking I am not plugging in a valid url for some reason?

Learn PowerShell Now

PowerShell 10 Years Anniversary videos

Powershell and SNMP (commands)

$
0
0

Hi

Its been a while since I did anything with SNMP, but I'd like to see if Powershell has any ways (cmdlets) etc on how to do simple SNMP gets, walks, sends traps.

(With Linux you get some useful command's snmpwalk etc)

So is there anything similar via powershell.

Ideally I want to avoid using any third-party tools as I've done many years ago, so not ruling that out.

Dee


Dee

GUYS please help!!

$
0
0
HI this is my Script 

 $DropDownArray1= @("No","Yes")

$DropDownArray2= @("TA","JE","HO","HA","NT","LP")

$DropDownArray3= @("NE","HB","PT","AY")

$OSDcomputerName="computername"

# Form building

Add-Type-AssemblyNameSystem.Windows.Forms

Add-Type-AssemblyNameSystem.Drawing

$Form=New-ObjectSystem.Windows.Forms.Form

$Form.width =500

$Form.height =400

$Form.Text =”Computer Name”

$Form.StartPosition ="CenterScreen"

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

foreach ($itemin$DropDownArray1)

{

  $ComboBox1.Items.Add($item)

}

$Form.Controls.Add($ComboBox1)

$Labal1=New-ObjectSystem.Windows.Forms.Label

$Labal1.Location =New-ObjectSystem.Drawing.Size(10,10)

$Labal1.Size =New-ObjectSystem.Drawing.Size(100,40)

$Labal1.Text ="Citrix ?"

$Form.Controls.Add($Labal1)

$ComboBox1=New-ObjectSystem.Windows.Forms.ComboBox

$ComboBox1.Location =New-ObjectSystem.Drawing.Size(140,10)

$ComboBox1.Size =New-ObjectSystem.Drawing.Size(130,30)

$ComboBox1.DropDownStyle =[System.Windows.Forms.ComboBoxStyle]::DropDownList;

$ComboBox1.Items.Clear();

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

ForEach ($Itemin$DropDownArray2) {

    

    $ComboBox2.Items.Add($Item) |Out-Null

}

$Form.Controls.Add($ComboBox2)

$Labal2=new-objectSystem.Windows.Forms.Label

$Labal2.Location =new-objectSystem.Drawing.Size(10,50)

$Labal2.size =new-objectSystem.Drawing.Size(100,40)

$Labal2.Text ="Computer Location ?"

$Form.Controls.Add($Labal2)

$ComboBox2=New-ObjectSystem.Windows.Forms.ComboBox

$ComboBox2.Location =New-ObjectSystem.Drawing.Size(140,50)

$ComboBox2.Size =New-ObjectSystem.Drawing.Size(130,30)

$ComboBox2.DropDownStyle =[System.Windows.Forms.ComboBoxStyle]::DropDownList;

$ComboBox2.Items.Clear();

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

ForEach ($Itemin$DropDownArray3) {

    

    $ComboBox3.Items.Add($Item) |Out-Null

}

$Form.Controls.Add($ComboBox3)

$Labal3=new-objectSystem.Windows.Forms.Label

$Labal3.Location =new-objectSystem.Drawing.Size(10,100)

$Labal3.size =new-objectSystem.Drawing.Size(100,60)

$Labal3.Text ="Company?"

$Form.Controls.Add($Labal3)

$ComboBox3=New-ObjectSystem.Windows.Forms.ComboBox

$ComboBox3.Location =New-ObjectSystem.Drawing.Size(140,90)

$ComboBox3.Size =New-ObjectSystem.Drawing.Size(130,30)

$ComboBox3.DropDownStyle =[System.Windows.Forms.ComboBoxStyle]::DropDownList;

$ComboBox3.Items.Clear();

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

 

$label4=New-ObjectSystem.Windows.Forms.Label

$label4.Location =New-ObjectSystem.Drawing.Point(10,160

$label4.Size =New-ObjectSystem.Drawing.Size(100,90

$label4.Text ="Insert 6 Numbers:"

$form.Controls.Add($label4

$textBox=New-ObjectSystem.Windows.Forms.TextBox 

$textBox.Location =New-ObjectSystem.Drawing.Point(140,160

$textBox.Size =New-ObjectSystem.Drawing.Size(130,30

$textBox.MaxLength =6

$form.Controls.Add($textBox

$textBox.Add_TextChanged({

    $this.Text =$this.Text -replace'\D'

})

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

$OKButton=new-objectSystem.Windows.Forms.Button

$OKButton.Location =new-objectSystem.Drawing.Size(200,250)

$OKButton.Size =new-objectSystem.Drawing.Size(100,20)

$OKButton.Text ="OK"

$OKButton.Add_Click({

$Form.DialogResult ="OK"

$Form.close()

})

$form.Controls.Add($OKButton)

$CancelButton=New-ObjectSystem.Windows.Forms.Button

$CancelButton.Location =New-ObjectSystem.Drawing.Size(200,300)

$CancelButton.Size =New-ObjectSystem.Drawing.Size(100,20)

$CancelButton.Text ="Cancel"

$CancelButton.Add_Click({

$Form.DialogResult ="Cancel"

$Form.close()

})

$Form.Controls.Add($CancelButton)

$Form.Add_Shown({$Form.Activate()})

$result=$Form.ShowDialog()

 

i am trying to get from this one "combobox1" selection = x, combobox 2 = y and on and on so at the end i would be able to build a computer name from the user selection

so x+y+z+m = computername


please i am trying for a long time to solve it i am not the best at powershell

thank you all

DNS add zone permission denied via powershell

$
0
0

Hello everyone,

I've tried the steps here which allows a user to add DNS records, however they cannot add DNS zones:

+ CategoryInfo          : PermissionDenied: (something.hlk:root/Microsoft/...rverPrimaryZone) [Add-DnsServerPrimaryZone], CimException
    + FullyQualifiedErrorId : WIN32 5,Add-DnsServerPrimaryZone

Any ideas?

Does Runspaces require Enable-PSRemoting enabled?

$
0
0

Hi, 

Does Runspaces require Enable-PSRemoting enabled on the querying machine and/or the queried machine?

I'm struggling to find an answer to this, and within all the documentation I read there's no mention that it is needed. 

I'm looking to simply use Runspaces to run WMI calls across multiple threads simultaneously. But not clear if this methodology will work if Remoting is not enabled. 

Thank you


Drive Space String Break

$
0
0

I am trying to take this:

$drivespace = gwmi win32_logicaldisk | Select @{LABEL='Drive ID';EXPRESSION={$_.DeviceID}}, @{LABEL='GB Free Space';EXPRESSION={"{0:N2}" -f($_.freespace/1GB)}} | Format-table -HideTableHeaders | Out-String

And I am trying to convert it into HTML using:

ConvertTo-Html $driveSpace

I am trying to have the Drive Space display the amount of free space left in one column of an HTML outputted table like this:

Drive Space 

C: 256.75

D: 120.50

But instead it is showing up like this:

Drive Space

C:  256.75 D:  120.50

How do I output this into one column where each string is separated?

Thank you in advance!


Powershell script to remove domain security group from local administrators of multiple servers.

$
0
0

Hi guys. 

I have a list of servers where one domain group is added to 'Local Administrators' of each server. Is there any power-shell script I can execute remotely for all these servers in one shot ?

Thanks in advance. 

Unable to index into an object of type System.Xml.XmlAttributeCollection - Error

$
0
0

I am receiving 'Unable to index into an object of type System.Xml.XmlAttributeCollection' error when I run the below Power Shell Script from my Windows 2008 server. Running the same script from my desktop works fine (Windows 7).

I am trying to read data from a SharePoint list, both server and desktop can access the SharePoint list in the browser however the Power Shell script is failing to run on the server side.

Am I missing any setting on the server side?

Code:

$xmlDoc = new-object System.Xml.XmlDocument
$query = $xmlDoc.CreateElement("Query")
$viewFields = $xmlDoc.CreateElement("ViewFields")
$queryOptions = $xmlDoc.CreateElement("QueryOptions")
$service = New-WebServiceProxy -Credential $Credential -uri <SharePoint URL>
$csv = $null
Do {
$list = $service.GetListItems(<Share Point List Name>, "", $query, $viewFields, '2000', $queryOptions, "") ## number is row limit
$csv += $list.data.row | select
$queryOptions.set_InnerXml('<Paging ListItemCollectionPositionNext="" />')
$queryOptions.ChildNodes.item(0).Attributes["ListItemCollectionPositionNext"].InnerText = $list.data.ListItemCollectionPositionNext
} While ($list.data.ListItemCollectionPositionNext)

iTextSharp - use fontawesome

$
0
0

Hello everyone,

i would like to create a pdf with itextsharp with the font "FontAwesome". But the icons just don't be displayed. Does anyone have an idea or another sample script?

# Import assembly: iTextSharp is from: https://sourceforge.net/projects/itextsharp
$Invocation    = (Get-Variable MyInvocation).Value
$PSDir         = Split-Path $Invocation.MyCommand.Path

Add-Type -Path "$PSDir\itextsharp.dll"


function first ([ScriptBlock]$Body) {
    $input | select -First 1 | % { & $Body }
}

function New-Font ([string]$font, [int]$size, [string]$direction="H"){
    [iTextSharp.text.pdf.BaseFont]::"IDENTITY_$direction" `
    | first { [iTextSharp.text.pdf.BaseFont]::CreateFont($font, $_, $true) } `
    | first { new-object iTextSharp.text.Font $_, $size }
}

# Register all fonts
[iTextSharp.text.FontFactory]::RegisterDirectories()

$pdf = New-Object iTextSharp.text.Document

$pdf.SetPageSize([iTextSharp.text.PageSize]::A4)
[void][iTextSharp.text.pdf.PdfWriter]::GetInstance($pdf, [System.IO.File]::Create("$Env:Userprofile\Documents\Label.pdf"))
$pdf.Open()


$p = New-Object iTextSharp.text.Paragraph
$p.Font = [iTextSharp.text.FontFactory]::GetFont("Arial", 8, [iTextSharp.text.Font]::NORMAL, [iTextSharp.text.BaseColor]::BLACK)
$Text = "FontAwesome:"
$p.Add($Text)
$pdf.Add($p)

$New_Font = New-Font -font "C:\Windows\Fonts\fontawesome-webfont.ttf" -size 8
$Chunk = New-Object iTextSharp.text.Chunk("\uf0d6", $New_Font)

$pdf.Add($Chunk)

$pdf.Close()

Looking for a script to find who is local admins group for all servers

$
0
0

Good Afternoon, 

I am Looking for a script to find who is local admins group for all servers.  There is a script in the following article, which I found to be helpful:

https://gallery.technet.microsoft.com/scriptcenter/Get-remote-machine-members-bc5faa57

The script will write up a new command to use called Get-LocalAdmin but it only allows to query one computer at a time.

Get-LocalAdmin "ServerFQDN" Is there a way to edit this script so that I can use the Import-CSV or some other method of querying groups of servers at a time? 

Also, can it be edited to allowed for a piped output to an Excel or Text file.

Thanks in advance.

Brian Dougherty

How do I configure the Connection Type on an existing virtual switch?

$
0
0

Hi,

I am trying to figure out how to configure the 'Connection Type" on an existing virtual switch named 'InternetConnection'. I used the command to create it.

New-NetLbfoTeam -Name InternetConnection -TeamMembers "NIC1","NIC3" -TeamingMode SwitchIndenpendent -Confirm:$false

But the above command gave me the default 'Connection Type': Private network

How can change an existing virtual switch to 'External network' with the first teaming 'Microsoft Network Adapter Multiplexor Driver'?

Thanks in advance for your help.

JC

Get-ADUser : The search filter cannot be recognized

$
0
0

Hi All,

I'm trying to update all users' attributes in our new domain. I'm getting this error when running the script. Still can't figure out what's the root cause. Any help will be greatly appreciated.

******Here's the error: ******

Get-ADUser : The search filter cannot be recognized
At C:\Users\secretlover.alvin\Documents\Update_User-Attributes.ps1:20 char:17
+     if($userX = Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)' ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

****************************************************************************************************************************

Import-Module ActiveDirectory
$error.clear()

cls


    #Search From CSV file.



write-Host "Updating all users' attributes......." -ForegroundColor Yellow


$users = Import-Csv -Path C:\Users\Public\NEW-AD_BMC_ALL.csv -Delimiter ';'


foreach ($user in $users) {

    $UserN = $user.displayName
    if($userX = Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" -Properties *) {

        Write-host "$UserN doesn't exist in AD" -ForegroundColor Green | Out-File C:\Users\Public\Logs.txt -Append

        $userprops=@{
            Title=if($user.Title){$user.Title}else{$null}

            displayName=$user.displayName

            manager=if($user.Manager){$user.Manager}else{$null}

            company=if($user.company){$user.Company}else{$null}

            Department=if($user.department){$user.department}else{$null}

            OfficePhone=if($user.Office){$user.OfficePhone}else{$null}

            City=if($user.City){$user.City}else{$null}

            StreetAddress=if($user.StreetAddress){$user.StreetAddress}else{$null}

            PostalCode=if($user.PostalCode){$user.PostalCode}else{$null}

            State=if($user.State){$user.State}else{$null}

            country=if($user.Country){$user.Country}else{$null}

            MobilePhone=if($user.MobilePhone){$user.MobilePhone}else{$null}

            ipPhone=if($user.ipPhone){$user.ipPhone}else{$null}

            telephoneNumber=if($User.telephoneNumber){$user.telephoneNumber}else{' '}

            EmailAddress=if($user.EmailAddress){$user.EmailAddress}else{$null}

            Office=if($user.Office){$user.Office}else{$null}

            Add=@{extensionattribute1=$user.extensionattribute1;ipPhone=$user.ipPhone}

            Replace=@{extensionattribute1=$user.extensionattribute1;telephoneNumber=$user.telephoneNumber}
        }

        $userX | Set-ADUser @userprops

    }else{
        Write-host "$UserN doesn't exist in AD" -ForegroundColor Green | Out-File C:\Users\public\logs.txt -Append
    }
}


Write-Host 'Done!' -ForegroundColor Yellow #-NoNewline



Power Shell Script to Pull Computer Names and Hard Drive serial numbers

$
0
0

Import-ModuleActiveDirectory



$lists

=Get-ADComputer-SearchBase"DC=rcen,DC=marines,DC=usmc,DC=mil,OU=6MCD,OU=MON_Montgomery,OU=Workstations,OU=Mobile"


-Filter{Description-Like"*MASS-1*"}-PropertiesDescription|SelectName


foreach

($lin$lists) {


$serials

=Get-WmiObjectwin32_diskDrive-ComputerName$l.name|selectSerialNumber


}


write-host

$serials

ERROR MESSAGE:

cmdlet Get-ADComputer at command pipeline position 1

Supply values for the following parameters

(type !? for Help.)

Filter:

following parameters:

(Type !? for Help.)

Filter: 

Update Mail attributes with PowerShell cmdlets

$
0
0

All,

I am new to PowerShell. 

Using PowerShell on one of our Active Directory Domain Controllers, I would like to update the following Object Attributes:

mail

mailNickname

proxyAddresses

targetAddress

Will someone give me the proper command/cmdlet I should use to do this?

Thank you,

T.J.

Is it possible to specify an array in a CSV file that can be read by Import-CSV?

$
0
0

We have a CSV file that is manually updated, and need to import that into PowerShell with Import-CSV for further processing.

Ideally (from a PS coding perspective) an array could be specified in the CSV; is this possible and if so what is the proper syntax?

For example I need something like this:

COL1,COL2,COL3  ## HEADERS

"value1", @("arrayv1","arrayv2","arrayv3"), "value3"

The number of items in the COL2 array would be variable.

 

PowerShell and Robocopy - Parsing Log for Event

$
0
0

Good evening everyone, I would like some feedback on using placing Application event logs from parsed Robocopy logs using Powershell. So for I've been able to Place an event log into Event Viewer, which states the log's file name and if there was an error or not. I haven't been able to place information from the log into the event.  There is another step, the log file from Robocopy will not end, it will continuously run gathering date of each transfer. (We are transferring incremental backups to an offsite location for our clients.)

So for I have found a few options:

http://thepowershellguy.com/blogs/posh/archive/2008/10/01/powershell-and-robocopy-part-5.aspx

Here is the code i used to perform my first example:

#requires -Version 2.0
## BEFORE you use this the FIRST time (only once per machine)
## you must run the following command elevated (as Administrator):
## New-EventLog Application Robocopy


Param(  [string]$LogPath  = "D:\",
        [string]$LogName  = "text.txt",
        [int]$ArchiveDays = 30
)
[string]$Log = Join-Path $LogPath $LogName
[string]$LogError = "$Log.ERROR.$(get-date -format 'yyyy-MM-dd-hhmmss')"
[string]$LogArchive = "$Log.ARCHIVE.$(get-date -format 'yyyy-MM-dd-hhmmss')"


$Errors = Select-String -Path $Log -Pattern 'ERROR .*0x0000.*$' -context 0,1 |
          Group-Object { $_.Context.PostContext } |
          Format-Table Count, Name -HideTableHeaders -AutoSize | Out-String
if($Errors) {
        write-eventlog Application -Source Robocopy -EventId 12 -EntryType Error -Message "$errors`n`nPlease check: $LogError"
        move $Log $LogError
} else {
        write-eventlog Application -Source Robocopy -EventId 1 -EntryType Information  -Message "Robocopy successful. Log archived: $LogArchive"
        move-item $Log $LogArchive
}

To sum up my request:

x - I would like to know if parsing information a continuously running log, if so, how?

x - within that hyperlink, would I be able to use that for what I'm trying to accomplish.

x - Ultimately I would like errors to be email to our helpdesk team, but i can find that out later.

Additional Information:

We have over 80 clients that use an incremental backup system(Zenith Arca) which is resting on a Windows 2003 DataCenter box. These backups are transferred offsite to a server, previously we used DeltaCopy, but saw a much greater improvement to use RoboCopy instead. 

If I'm missing any needed information, please let me know.  Thanks all!




$Profiles = $ProfileManager.GetEnumerator()

$
0
0

Hi

Is it possible to target specific users with the above PowerShell in a specific company in AD?

cheers

Shane

Viewing all 21975 articles
Browse latest View live


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