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

Powershell/sharepoint remove-pnplistitem

$
0
0

Hi,

I'm new to powershell and sharepoint. I can add a publishingpage to sharepoint using powershell. Now I also want to remove the publishingpage using powershell, but that is the part I don't seem to get to work.

#Config Variables
$SiteURL = "https://somesharepointsite"
$PageName = "1234.aspx"
$PageTitle= "SomeTitle"
$PageTemplate = "BlankWebPartPage"
$PageContent="somecontent"
$VacancyHours=36
$SomeId="123456"
#Get Credentials to connect
#$Cred = Get-Credential
Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    #Create a publishing page
    Add-PnPPublishingPage -PageName $PageName -Title $PageTitle -PageTemplateName $PageTemplate
    #Get the Page
    $Page = Get-PnPListItem -List "Pages" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>$PageName</Value></Eq></Where></Query></View>"


    #check-out the page for editing
    Set-PnPFileCheckedOut -Url $Page["FileRef"]
    #Set Content Type
    Set-PnPListItem -List "Pages" -Identity $Page -ContentType "Vacancy"

    #Set Page Content
    Set-PnPListItem -List "Pages" -Identity $Page -Values @{"PublishingPageContent"=$PageContent; "VacancyHours"=$VacancyHours; "SomeId"=$SomeId}
    #check-in the page
    Set-PnPFileCheckedIn -Url $Page["FileRef"] -CheckinType MajorCheckIn
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

After I made the page, I want to remove it again. I think it's something with remove-pnplistitem, but i cannot get it to work. Among other things I tried:    

#Remove publishing page
Remove-PnPListItem -List "Pages" -Identity $PageName
Thanks in advance.



Is there a way to set Target Type when creating a shortcut to network folder?

$
0
0

I have a script that creates a shortcut to a network drive folder that I am deploying through SCCM. The short cut gets created but with the target type set as "File" instead of "File Folder" and does not work. Here is the script:

1   [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") 

3   Remove-Item "C:\Users\*\desktop\OR Resources.lnk" -Force
4   Copy-Item ".\icons\OR Resources.ico" "C:\Windows" -force


7   $WshShell = New-Object -ComObject WScript.Shell

9   $ORResources = $WshShell.CreateShortcut("c:\users\public\desktop\OR Resources.lnk")
10  $ORResources.TargetPath = "\\fmdata01\sdrive\shared\OR_Resources\"
11  $ORResources.IconLocation = "C:\Windows\OR Resources.ico"
12  $ORResources.Save()

Any suggestions would be very helpful. Thank you

Aide pour la création d'un script pour automatiser la priorisation du réseau filaire au wifi

$
0
0

Bonjour,

Je souhaiterais pouvoir scripter la priorisation du wifi par rapport aux connexion ethernet, pour se faire, je passe par les commandes get-netipinterface et set-netipinterface.

Aujourd'hui je récupère ma liste d'objet avec leurs valeurs sous le format ci dessous via get-netkipinterface | select-objet ifindex, interfacealias, interfacemetric )

IfIndex      InterfaceAlias  InterfaceMetric

12             Ethernet 2           30

9               Wi-Fi                  25

24             Ethernet 7           30

Je souhaiterais pouvoir faire une vérification que mon interfacealias est bien -eq à "Wi-Fi" et si c'est le cas faire l'intégrer dans une variable pour ensuite lancer un set-netipinterface -IfIndex $index -InterfaceMetric 50

Le souci, je ne parviens pas à agir que sur mon ifindex dans le cas ou sa valeur "interfaceAlias" est -eq à Wi-Fi.

Auriez vous une idée de comment je pourrais formuler mon script ? (je bloque surtout sur le fait d'agir que sur une ligne, je pense que je bloque sur la façon de faire (foreach?))

Merci par avance

Task Scheduler, Execute powershell script with a command

$
0
0
I have a powershell api script that changing wifi passwords in Meraki.
Now i want to add this script to Task Scheduler and execute it with a specific command line, for example:

In "Action" section i'm always putting those lines:

    Program/script : Powershell.exe
    Add arguments : -ExecutionPolicy Bypass C:\Policies\Meraki\ChangePass.ps1

But this won't work here, because this script can be executed only when using this command:

    .\ChangePass.ps1 -site "Building1" -ssid "Wifi-Guest" -action "Change"

Thanks for help

How to delete printer in a domain user profile

$
0
0

Hi,

iam new into powershell. Iam trying to figure to remove all printers on a workstation/domain user

I have written a small script where i get the list of all the printer on a domain. Removed any policies which removed all the printers but some user have installed manually the printers (shared) and local printers. Somehow the script does not show them. I ran is admin and highest level of domain administrator no luck. I cannot believe that as an administrator i cannot see or delete those printers via power shell.

See script for making a list which printer is installed on which computer. I will modify the result then delete those printers. Like mention shared and local printers do not show up. 

Get-Content -Path c:\ListOfComputers.txt | ForEach-Object {
if (Test-Connection $_ -Count 1 -Quiet) {
Get-Printer -ComputerName $_ | Select-Object -Property Computername,Name | Export-Csv -Path c:\PCPrinterList.csv -NoTypeInformation -Append
} else {"Computer $_ offline" >> c:\OfflinePCs.txt
}
}


This scripts would remove the printers according to list

Import-Csv c:\PCPrinterList.csv |`
    ForEach-Object {
	Remove-Printer -ComputerName $_.ComputerName -Name $_.Name
}

Any idea how can get it done in powershell? 

Indian


How to create a server with password preset?

$
0
0

Hi,

Our application in Linux box trying to create a windows server with password presert in the client's infra which is built on openstack. It is creating the server, but then it is generating random password and returning the random password. Funny part is that the server is prompting for a new password set up for the first time, its totally ignoring the pre-set password, plus its returning the random password. How can we address this?

regards

Nambi

System and Dates format

$
0
0

Hello,

I have an CSV that has a text column that is a Date. All fine until now.

I want to execute some scripts against some remote computers ( that have different time formats defined) and i need this date to be translated in the System Format the computer understands. How can i do that?

I was tinkling of transforming into CSV maybe in a generic value that is recognized by all computers and then each computer where i run the script to transform it as needed.
Maybe to File or LDAP Time?

Any ideas?

Thank you

Unable to install multiple KBArticle on window Servers

$
0
0

Hi Support,

I am unable to install multiple KBArticle on Widows Servers but this command is working fine.

Working Command:

Install-WindowsUpdate -KBArticleID KB4535104 -Confirm:$false -AutoReboot

Error Command: When adding multiple KBArticle

Install-WindowsUpdate -KBArticleID KB4535104,KB4486105  -Confirm:$false -AutoReboot


Resolve-DnsName and TXT records

$
0
0

Hello guys, Can anyone help me to create a ps script to check DNS TXT records? I spent a long time trying to find a way to cut the results, but I could not find it.

How can I bring just a piece of this string? removing un necessary data and leaving just what I want.

PS C:\Windows\system32> Resolve-DnsName globo.com -Type TXT | ft Strings -HideTableHeaders -Wrap

{facebook-domain-verification=az0i8tu9502l8fbi1usht04qdsjn4m}
{v=spf1 include:_gl1.globo.com include:_lw1.globo.com include:_lw2.globo.com include:_spf.directtalk.com.br
include:_spf.salesforce.com -all}

I need to create a list with all "include:" results like this:

gl1.globo.com
lw1.globo.com
lw2.globo.com
spf.directtalk.com.br
spf.salesforce.com

 

Thanks in advanced


Thiago Zanardo

Aide pour la création d'un script pour automatiser la priorisation du réseau filaire au wifi

$
0
0

Bonjour,

Je souhaiterais pouvoir scripter la priorisation du wifi par rapport aux connexion ethernet, pour se faire, je passe par les commandes get-netipinterface et set-netipinterface.

Aujourd'hui je récupère ma liste d'objet avec leurs valeurs sous le format ci dessous via get-netkipinterface | select-objet ifindex, interfacealias, interfacemetric )

IfIndex      InterfaceAlias  InterfaceMetric

12             Ethernet 2           30

9               Wi-Fi                  25

24             Ethernet 7           30

Je souhaiterais pouvoir faire une vérification que mon interfacealias est bien -eq à "Wi-Fi" et si c'est le cas faire l'intégrer dans une variable pour ensuite lancer un set-netipinterface -IfIndex $index -InterfaceMetric 50

Le souci, je ne parviens pas à agir que sur mon ifindex dans le cas ou sa valeur "interfaceAlias" est -eq à Wi-Fi.

Auriez vous une idée de comment je pourrais formuler mon script ? (je bloque surtout sur le fait d'agir que sur une ligne, je pense que je bloque sur la façon de faire (foreach?))

Merci par avance

AD User Attributes - CSV Update Script - telephoneNumber

$
0
0

Hi All,

I've been using the script below without major issues for a while, I've added and removed additional attributes successfully since I started using the script, now when I try adding another line to update the attribute "telephoneNumber" the script hangs on this >> and doesn't go any further.

I am adding -  Telephone Number = $user.telephoneNumber

     

Foreach($user in (Import-CSV c:\psscripts\userlist.csv)){
$props = @{

           Identity      = $user.SAMAccountName
           Title         = $user.Title
           Office        = $user.physicalDeliveryOfficeName
           Department    = $user.department
           Mobile        = $user.mobile
           Manager       = $user.Manager
           Email         = $user.mail
}
Set-ADUser @props
}

I have also tried updating only telephone number using the script below but it also hangs - 

Foreach($user in (Import-CSV c:\psscripts\userlist2.csv)){
$props = @{

           Identity      = $user.SAMAccountName
           Telephone Number = $user.telephoneNumber
}
Set-ADUser @props
}

Invoke-Restmethod - intermittent unauthorized error with certificate option

$
0
0
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Uri = 'https://somerandomserver.com'

$Store = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My, "localmachine")
$Store.Open("MaxAllowed")
$Certificate = $Store.Certificates | Where-Object Thumbprint -EQ "xxxxxxx"
Invoke-RestMethod `
-Certificate $Certificate `
-ContentType 'application/json' `
-Uri $uri

I have configured access to the apiand trying to access the apiusing the certificate configured with. It is throwing unauthorized error intermittently, Am I missing something when passing the parameters to invoke-restmethod?

Set-ADUser a few ExtensionAttributes

$
0
0

Hello,

I make a script to change properties on users from csv and I need to modify a few extensionAttribute.

My script looks that:

Set-ADUser `
-Identity $sama `
-Company $company `
-StreetAddress $address `
-City $city `
-PostalCode $postalcode `
-Add @{extensionAttribute2="$extAtr2" `
-Add @{extensionAttribute3= "$extAtr3" `
-Add @{extensionAttribute4= "$extAtr4" `
-Add @{extensionAttribute5= "$extAtr5" `
-Title $job `
-Department $department `
-Manager $manager

But "-add" parametr is underlined, how to improve it to be correct?

JRV a condescending piece of **** - who agrees?

$
0
0

Just had a run in with your oh so friendly moderator.

Who agrees that this guy is a tosspot?

A parameter cannot be found that matches parameter name 'Title' when updating Exchange users via powershel

$
0
0

# Updates Exchange user attributes from CSV file

$Credential = Get-Credential Connect-ExchangeOnline -Credential $Credential # Load data from file.csv $EXUsers = Import-csv file_path # Count variable for number of users update $count = 0 # Go through each row that has user data in the CSV we just imported ForEach($User in $EXUsers) { # Ppopulate hash table for Get-EXUser splatting: $GetParams = @{ Identity = $User.Username } # Initialize hash table for Set-ADUser splatting: $SetParams = @{ Title = $User.Title } # Check to see if the user already exists in AD. If they do, we update. if ( Get-EXORecipient @GetParams) { # Set User attributes Set-User @SetParams -WhatIf # Print that the user was updated Write-Host -ForegroundColor Yellow "$User - User attributes have been updated." # Update Count $count += 1 } } # Print the number of updated users Write-Host $count "Users have been updated" -ForegroundColor Green

Error Message:

A parameter cannot be found that matches parameter name 'Title'.+ CategoryInfo          : InvalidArgument: (:) [Set-Mailbox], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Set-Mailbox+ PSComputerName        : outlook.office365.com

I have written a script to update Exchange user mailbox attributes but I get this error.

I think I am using the wrong cmdlet but I am not sure which one I need to update the title

attribute.



PowerShell - Get Folder ID from String

$
0
0

Hi All,

I am trying to write a powershell script that will get the contents of a folder which contains zip file and then move these to the corresponding folders.

For example d:\datadownload contains;

data-230809_0008888.zip
data-230809_0008878.zip

I wont a script that will move the file data-230809_008878.zip to d:\data\0008878.

The script doesn't need to unpack it but just needs to move it.

[string[]]$files = Get-ChildItem -Path "d:\datadownload" | Select -ExpandProperty name

foreach($file in $files)
{
    [string[]]$folder = $file.Split("_",8)
    write-host $file.Split("_")
}

This is what I have currently started with but I can't figure out how to remove everything other than the bit of information that I need.

Could someone point me in the right direction of where to go next. I was looking at using some kind of 'substring' but there doesn't seam to be a substring option in PowerShell.

Regards,

Tom


TPark IT Technician

Powershell Script to Add Text to Host files

$
0
0

Need a powershell script to add host entries to an existing host file for a list of servers.

It should pull from something like servers.txt which will have IP Address or hostname of the server(s) getting updated, add entries to the host file currently located in the standard windows directory, and give an output to a document such as Hosts-Changed.txt of Server that that was updated.

Powershell script to append multiple entries on Windows Hosts file to list of servers?

$
0
0
I Have a list of servers which requires adding 2 entries on hosts file remotely but could'nt find the script.

CSV Files Error: "String was not recognized as a valid DateTime."

$
0
0

I have an odd one. I have written a script that will work through a bunch of csv files which are being generated from a Nimble Infosight lab, determine the hours to be between 07:00 and 17:55 and give me the max, min and average of the read, write iops and read, write throughputs.

It has worked previously fine.

For some reason, there are certain csv files where i am getting an error saying the below. Out of a folder with 22-23 csv files, maybe 2-5 do not work now for some reason I cannot work out:

Cannot convert value "13/04/2020 03:31" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At C:\Temp\IOPsWeekdays.ps1:16 char:5
+     (([datetime]$_.ts).Hour -gt 7 -and ([datetime]$_.ts).Hour -lt 17) ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

Here is the script I am using:

#run the below cmd in an elevated powershell cmd window to allow unsigned scripts to execute
Set-ExecutionPolicy unrestricted

#set path to pick up ,csv`s
$Path = "C:\Users\blahblah\\Servername\volumepool\volume\April"

$Files = Get-ChildItem -Path $Path -Filter '*.csv' | Select-Object FullName

Write-Output  "Processing $($Files.count) Files"

foreach ($File in $Files)
{
    Write-Output $File.FullName
    $csv = Import-Csv -Path  $Files.FullName | 
    Where-Object{
    (([datetime]$_.ts).Hour -gt 7 -and ([datetime]$_.ts).Hour -lt 17) -or 
    (([datetime]$_.ts).Hour -eq 17 -and ([datetime]$_.ts).Minute -lt 55)
                }
    $csv.read_iops | measure -Maximum
    $csv.read_iops | measure -Minimum
    $csv.read_iops | measure -Average
    $csv.write_iops | measure -Maximum
    $csv.write_iops | measure -Minimum
    $csv.write_iops | measure -Average
    $csv.read_mbps | measure -Maximum
    $csv.read_mbps | measure -Average
    $csv.write_mbps | measure -Maximum
    $csv.write_mbps | measure -Average
}

I can try and add a couple of csv files if this lets me add attachments later.

Any help would be appreciated.

Thanks

MFA Partner portal script issue

$
0
0

I'm having some issues with this script, it wont export any data, I'm looking to export a list of clients which have 2FA enabled with the partner portal , Can someone point me in the right direction

Connect-MsolService

$clients = Get-MsolPartnerContract -All
$mfaStatus = $_.StrongAuthenticationRequirements.State 
$methodTypes = $_.StrongAuthenticationMethods 
$Date = Get-Date -format "dd-MM-yyyy"

ForEach ($client in $clients) {
$Result=@() 
$users = Get-MsolUser -All
$users | ForEach-Object {
$user = $_
$mfaStatus = $_.StrongAuthenticationRequirements.State 
$methodTypes = $_.StrongAuthenticationMethods 
 
if ($mfaStatus -ne $null -or $methodTypes -ne $null)
{
if($mfaStatus -eq $null)
{ 
$mfaStatus='Enabled (Conditional Access)'
}
$authMethods = $methodTypes.MethodType
$defaultAuthMethod = ($methodTypes | Where{$_.IsDefault -eq "True"}).MethodType 
$verifyEmail = $user.StrongAuthenticationUserDetails.Email 
$phoneNumber = $user.StrongAuthenticationUserDetails.PhoneNumber
$alternativePhoneNumber = $user.StrongAuthenticationUserDetails.AlternativePhoneNumber
}
Else
{
$mfaStatus = "Disabled"
$defaultAuthMethod = $null
$verifyEmail = $null
$phoneNumber = $null
$alternativePhoneNumber = $null
}
$Result += New-Object PSObject -property @{ 
UserName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
MFAStatus = $mfaStatus
AuthenticationMethods = $authMethods
DefaultAuthMethod = $defaultAuthMethod
MFAEmail = $verifyEmail
PhoneNumber = $phoneNumber
AlternativePhoneNumber = $alternativePhoneNumber
}
}
}


$Result | Select CompanyName,UserName,MFAStatus,MFAEmail,PhoneNumber,AlternativePhoneNumber | Export-Csv -notypeinformation -Path "C:\PowerShell Scripts\MFAreport$Date.csv"

Viewing all 21975 articles
Browse latest View live


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