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

How to get script to stop if I press Cancel

$
0
0

I have a script that has popup boxes that ask for information.  There is an OK and Cancel button on each.  I want at anytime a Cancel is pressed for the script to stop.  Any idea how to do that?  I have about 4 popup boxes but if I press cancel on any of them I want it to stop.

Thanks,


Expand PS variable from xml Attribute

$
0
0

Hi

I'm trying to expand a string that comes from an XML.attribute, but i cannot get it Work.

How do i do that?

$Config = @{"Domain" = "domain.local"
}

$testxml = [xml]'
<Config><Test Certificate="CN=*.$($Config.Domain)" /></Config>
'

$test = $testxml.SelectNodes('//Config/Test')
foreach ($attr in $test.attributes)
{
    #How do I expand the variables in the attribute.value? it should expand to: XML attribute: Certificate CN=*.domain.local
    Write-Host "XML attribute: $($attr.Name) $($attr.Value)"
}

SQLPS error related to powershell version

$
0
0

Hello,

After we've upgraded to SQL 2016 and deployed SQL management studio 2016 on some servers, SQLPS module stopped working. Once I try to launch SQLPS in powershell, it displays following error message:

Import-Module : The version of the loaded PowerShell is '2.0'. The module 'D:\Microsoft SQL Server (x86)\130\Tools\Powe
Shell\Modules\SQLASCMDLETS\SQLASCMDLETS.psd1' requires a minimum PowerShell version of '4.0' to execute. Please verify
the installation of the PowerShell and try again.
t D:\Microsoft SQL Server (x86)\110\Tools\PowerShell\Modules\SQLPS\SqlPsPostScript.ps1:8 char:33
 if($m -ne $null) { Import-Module <<<<  $m -Global }
   + CategoryInfo          : ResourceUnavailable: (D:\Microsoft SQ...LASCMDLETS.psd1:String) [Import-Module], Invalid
  OperationException
   + FullyQualifiedErrorId : Modules_InsufficientPowerShellVersion,Microsoft.PowerShell.Commands.ImportModuleCommand

Thing is, that the powershell version installed on the server is version 5.0:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  117

But once I invoke the SQLPS that ends with error, the command $PSVersionTable.PSVersoin throws following value:

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

This happened only on servers where the SQL Management Studio 2016 was deployed. Does anyone else experience this problem? Any idea how to fix it?

Thanks,

Daniel

How to split column into multiple columns from existing CSV

$
0
0

I am getting the CSV with following format

CreationDate,UserIds,Operations,AuditData
2017-01-30T16:52:35.0000000Z,user@domain.com,FileRenamed,"{""CreationTime"":""2017-01-30T16:52:35"",""Id"":""12345678-347d-452e-eb13-08d44930643b"",""Operation"":""FileRenamed"",""OrganizationId"":""12345678-a3da-442a-930b-235cac24cd5c"",""RecordType"":6,""UserKey"":""i:0h.f|membership|12345678f9b5cf5da@live.com"",""UserType"":0,""Version"":1,""Workload"":""OneDrive"",""ClientIP"":""123.123.123.12"",""ObjectId"":""https:\/\/my.domain.com\/personal\/user_domain_com\/Documents\/Catalian - Document tècnic OD4B.docx"",""UserId"":""user@domain.com"",""EventSource"":""SharePoint"",""ItemType"":""File"",""ListId"":""12345678-98ac-4592-93fc-7f6246e348fd"",""ListItemUniqueId"":""12345678-3e99-418f-89a0-f9ca965adda0"",""Site"":""12345678-81f8-42b6-93f1-9eea244c2ce9"",""UserAgent"":""Microsoft SkyDriveSync 17.3.6743.1212 ship; Windows NT 6.1 Service Pack 1 (7601)"",""WebId"":""12345678-07f7-482a-8fc2-dbbb7ac68474"",""DestinationFileExtension"":""docx"",""SourceFileExtension"":""docx"",""DestinationFileName"":""Catalian Document tècnic OD4B.docx"",""DestinationRelativeUrl"":""Documents"",""SiteUrl"":""https:\/\/my.user.com\/personal\/user_domain_com\/"",""SourceFileName"":""Catalian - Document tècnic OD4B.docx"",""SourceRelativeUrl"":""Documents""}"

If you noticed that first three columns are already comma delimited, but forth column again containing more parameters. I want to split this column again in multiple columns with the header.

Everytime it is very difficult to convert in excel, time consuming job especially when you are getting this csv twice in day.

Now I want to generate another CSV with following columns in comma delimited columns as mentioned below

CreationDate,UserIds,Operations,AuditData,CreationTime,ID,Operation,OrganizationID,RecordType,UserKey,UserType,
Version,Workload,ClientIP,ObjectID,UserID,EventSource,ItemType,ListID,ListItemUniqueId,Site,UserAgent,WebID,
DestinationFileExtension,SourceFileExtension,DestinationFileName,DestinationRelativeUrl,SiteUrl,SourceFileName,
SourceRelativeUrl


Please advise how can I read and convert fourth column into multiple coluns with the header using powershell script.

Timeout while Invoke-Expression powershell

$
0
0

Hi, is it possible to set timeout while invoke expression in powershell for example:"

$timeoutInSecond = 30;

while($timeout < $running time){

Invoke-Expression "C:\test.exe -verbose -page"

}

run Office Online question

$
0
0

I need to do the following.    Machine abc does not have Office installed locally.   A user who is logged into machine abc goes to a network share and double clicks on an Office doc (.xlsx, docx etc....)   I need that document to launch in Office.Live.com

Now, I can modify the File Association and point any .xlsx or docx file to run a custom PowerShell Script.  This PowerShell script looks like this:  

(if an Excel file was clicked on.......)

if (Test-Path  "C:\Program Files\Microsoft Office 15\root\office15\Excel.exe"){start-sleep -m 1}
ELSE {cmd.exe /c "C:\Program Files\Internet Explorer\iexplore.exe" "https://office.live.com/start/Excel.aspx?"}

My issue is this does not open the document that was actually clicked on.    How would that be done?   So the file could be something like this:    \\Server\Share\SubFolder\SubFolder2\Expense Report for January 2017.xlsx

How would you launch that in Office.Live?


mqh7

Want to know more about Powershell DSC

$
0
0

Hi Friends,

I am very new to Powershell DSC and I would like to implement and test it, so I would like to know more on below points :

1. Why do we need PowerShell DSC ? 

2. What are the PowerShell DSCs advantages over other automation tools ? or any unique property or functionality is highlighted ?

3. When i explored about some tasks using PowerShell DSC, I can do the same with help of GPOs. Example : I can create a good windows patch management environment using DSC (something like automating the patching on servers) This same job can be done by defining policies on GPO. So what would the advantage over this ?

Your answers/suggestions/feedbacks are most welcome

Thanks

Arun 

Should wildcard work with start-bitstransfer?

$
0
0

Should wildcard work with start-bitstransfer?

I am very new to Powershell. I am trying to see if it is a realistic option to HTTrack for spidering a site which it no longer seems able to reach.

According to (rather old) documentation at https://technet.microsoft.com/en-us/library/dd819420.aspx, wildcards should work with start-bitstransfer.

The quoted example is

Start-BitsTransfer -Source http://server01/servertestdir/*.* -Destination c:\clienttestdir\

Excellent, just the sort of thing I need.

For the site I am looking at I know that

start-bitstransfer -source http://mjcarchive.www.idnet.com/schedules/250to299/Schedule_299MF.pdf -destination G:\buses\

works and copies the single file across.

But if I amend it to

start-bitstransfer -source http://mjcarchive.www.idnet.com/schedules/250to299/Schedule_299M*.pdf -destination G:\buses\

or any other form involving wildcards, I get an error:-

At line:1 char:1
+ start-bitstransfer -source http://mjcarchive.www.idnet.com/schedules/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Start-BitsTransfer], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand

I have tried something similar on one of my owen websites, with similar results.

So ... does use of a wildcard actually work with start-bitstransfer on current Powershell (which came with my Win 10 upgrade in Summer 2016)? Or am I doing something really stupid?


How to corrupt WMI repository

$
0
0
There is a lot of articles about how to fix a corrupt WMI repository, but nothing about how to make it corrupt. I would like to destroy it to test a PS script, which could fix it.

Mounting/Dismounting ISO

$
0
0

I ran into something in regards to mounting/dismounting ISOs that is confusing me.  I can mount (Mount-DiskImage) an ISO file multiple times, and each one is provided with a new drive letter.  But when I dismount (Dismount-DiskImage) the ISO, it dismounts the first one mounted first and then the second one.  This is making things difficult.

Here is the issue.  I want to mount an ISO to access the contents.  I can extract the drive letter and then access any directory on the mounted volume.  At the end, I dismount the ISO.  All works without any issue.

But, if another script running on the same computer mounts the same ISO, it is properly mounted with a different drive letter.  That other script starts accessing the ISO.  At the end, the other script dismounts the ISO.

Problem:  Whichever script finishes first dismounts the first mounted ISO.  So if another script was running when I started, and I finished first, when I dismount 'my copy of' the ISO, the other script  no longer has access to its volume.

Is there a way to ensure I dismount the volume I mounted?  I don't see anyway to specify what to dismount other than the -ImagePath used to mount it?  I tried -DevicePath and it doesn't help, either.

Thanks for your insights.


. : | : . : | : . tim

Want to be the Microsoft TechNet Windows PowerShell Guru for February 2017?

$
0
0

February 2017 Guru, it’s time to share great skills as a TechNet Wiki article and WIN medal(s). Medals? Yes, you can share multiple articles in the same or different categories! Now, navigate to TechNet Guru Competition February 2017 to choose your categories and if it’s not listed add your content in Miscellaneous Category!

All you have to do is add an article to TechNet Wiki from the field of your interest. Something that fits into one of the categories listed on the submissions page. Copy in your own blog post, a forum solution, a white paper, or just something you had to solve for your own day’s work today.

A snippet you share can make you a February 2017 TechNet Wiki Guru in your favorite category and this is official Microsoft TechNet recognition!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations to TechNet Wiki.
2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you’ve contributed).
3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favorite technology will help us learn the active members in each community. 

Feel free to ask any questions below.

More about TechNet Guru Awards.


signature  Ronen Ariely
 [Personal Site]    [Blog]    [Facebook]   [Linkedin]

Compare dates and extract the last 10 days data

$
0
0
This is my csv:
2016-05-03 18:12:39 +0100|6339|3P System Srl(Fiesso D'artico,Italy)|32.43|17721|1672
2016-01-03 18:12:39 +0100|6339|3P System Srl(Fiesso D'artico,Italy)|32.43|17721|1672
2017-02-03 18:12:39 +0100|6339|3P System Srl(Fiesso D'artico,Italy)|32.43|17721|1672
2017-02-02 18:12:39 +0100|6339|3P System Srl(Fiesso D'artico,Italy)|62.43|62721|72
2017-02-02 18:15:22 +0100|6339|3P System Srl(Fiesso D'artico,Italy)|62.41|27908|2670
This is my script:
$target = '10'

$datetarget = (Get-Date).addDays(-$target).ToString('dd-MM-yyyy')

$HTML = $result | Select-Object @{n='Date'; e={ ([datetime]$_.Date).ToString('dd-MM-yyyy') }},
                                @{n='Time'; e={ ([datetime]$_.Date).ToString('HH:mm:ss') }},
                                Id,
                                Provider,
                                @{n='Ping ms'; e={ "{0:N2}" -f ($_.Ping / 100) }},
                                @{n='Download'; e={ "{0:N2}" -f ($_.Download / 1000) }},
                                @{n='Upload'; e={ "{0:N2}" -f ($_.Upload / 1000) }} |
                                Where-Object { $_.Date -gt $datetarget }

$HTML = $HTML | Where-Object { $_.Date -gt $datetarget }

$HTML | Format-Table -AutoSize 


I want display only the last 10 days results of my csv, thanks for help
 

Hard one: setting WiniNet cookies

$
0
0

Dear experts,

So, I've used Invoke-WebRequest using the WebSession parameter on a website that gives me some cookies. This works, my cookie container is filled with the proper cookies and names.

I then want to store the cookies using SetInternetCookie using WiniNet. This works sometimes, I don't know 

$relevantCookies = $cookies.cookies.GetCookies("subdomain1.domain.com")

$source=@"
using System.Runtime.InteropServices;
namespace Cookies
{

    public static class setter
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool InternetSetCookie(string url, string name, string data);

        public static bool SetWinINETCookieString(string url, string name, string data)
        {
            return setter.InternetSetCookie(url, name, data);
        }

    }

}
"@

$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compilerParameters.CompilerOptions="/unsafe"
Add-Type -TypeDefinition $source -Language CSharp -CompilerParameters $compilerParameters
foreach($cookie in $relevantCookies){
    write-host "setting $($cookie.Name)"
    [Cookies.setter]::SetWinINETCookieString("https://$($cookie.Domain)",$cookie.Name,$cookie.Value)
}

I have 2 cookies in $cookies.cookies.GetCookies;

subdomain1.domain.com

domain.com

Running this code results in true, false. In other words, the last cookie fails to get set. Does anyone know how i can get the error code instead of just False? I tried adding a GetLastError function but got syntax compiler errors....my C# isn't that great yet.



Use copy-item to backup files

$
0
0

When using ROBOCOPY with /m switch, it only copy files that were modified (Archive attribute is set) and reset the Archive attribute after copying.

Is there a way to do it by using Copy-Item? I just need to copy files modified since last backup. Thanks.

issue passing variable to subscope in foreach statement

$
0
0

ps version=5.0

objective:  the gist of what I'm trying to do is start Hyper-V guests remotely usingInvoke-Command in a foreach loop, populated by Import-CSVcalling an external file that maintains a list of the host (computername)-guest(vmname) relationships.

issue:  the iterating variable initialized in the foreach loop seems to be uninitialized in the nested "scriptblock" for theInvoke-Command statement.  I tried passing said variable via the "-ArgumentList" option but the result is the same; the value for the VM name comes up as null (appears uninitialized, lost between foreach loop object and invoke-command's scriptblock).

So I have a 2-field comma-separated file, "host_guest.vmlist" with the headerline:

hostFQDN,guestVMName

and contents like

edge1.corp.contoso.com,inet1

the script I'm trying to run:

$host_guest=import-csv -path ${PSScriptRoot}\host_guest.vmlist
write-output "the contents of `$host_guest are: " #sanitycheck
$host_guest
foreach ($vm in $host_guest)
{    invoke-command -computername ${vm}.hostFQDN -scriptblock {start-vm -name ${vm}.guestVMName -verbose} -argumentlist $vm
}

This yields the following error (underlined):

Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
    + CategoryInfo          : InvalidData: (:) [Start-VM], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.HyperV.PowerShell.Commands.StartVMCommand
    + PSComputerName        : mp1.corp.contoso.com

now trying to recreate each step of the process, parsing, evaluation, execution--I've tried various things to make sure values of the variable are evaluated and populated using "write-output" as a test in the interactive shell environment,  but as soon as I try to use it with invoke-command--ERROR--CANNOT COMPUTE!!!

What am I doing wrong?


Get-TfsWorkspace : Unable to determine the current workspace based on the path : C:\TFS

$
0
0

Get-TfsWorkspace C:\TFS

Hello,

My tfs is mapped to C:\TFS.  When I run Get-TfsWorkspace C:\TFS

I get an error message "Get-TfsWorkspace : Unable to determine the current workspace based on the path : C:\TFS"

I deleted the workspace and recreated but did not help.

Did anyone ever had this same problem?

Thank you

network path was not found when use invoke

$
0
0

Prompt error of "Exception calling "Invoke" with "2" argument(s): "The network path was not found" " when I'm try to change password of administrator in remote server by below command at 1st time, but works if I triggered in 2nd time.

$admin=[ADSI]("WinNT://" + $strComputer + "/administrator,user")
$admin.psbase.invoke("SetPassword",$Password)

I tried add one more command line test-connetion or start-sleep but still the same.

Any solutions would be much helpful, thanks.

Cheers

Joe

Use PS to create new local admin on clients (Servers)

$
0
0

We currently perform the following using GPO:

* Disable the local Administrator user on the client.

* Create a new user on the client named "AABBCCDD".

* Set the password for user "AABBCCDD" to "XXYYZZ123".

* Place the new user "AABBCCDD" into the local Administrators group on the client.

Microsoft have removed this functionality as the password it sent encoded but still retrievable so I'm looking for a new solution. I've looked at LAPS but that does not do all of the above. Can this be done using PowerShell?

The criteria is:

* The password for user "AABBCCDD" must not be accessible to anyone other than the Domain Admins.

* All client users called "AABBCCDD" will be given the same password.


| +-- JDMils |

Get-Content: Permission denied

$
0
0

Hi there

Why do I get on the following script an error alert?:

$Affectedfile = Get-Content C:\Users\localhost\Desktop\Source # affected file name list(Full Path)


foreach($s in $Affectedfile)

{

[string[]]$file = [io.path]::GetFileNameWithoutExtension("$s") #searching file

$find = Get-ChildItem -Path C:\Users\localhost\Documents\Test_Backup_Full -Include $file -Recurse # The Path here is restrored Backup location

$SourceDirectory = $find.Directoryname

$sourcefile = $find.FullName

$targetfile = $s.Split("\")[-1]


$TargetDirectory = $s.trim($targetfile)


Write-host " '"$targetfile"' will be replaced with  '"$file"' on the folder '"$TargetDirectory"'"

Copy-Item -Path $sourcefile -Destination $TargetDirectory -Confirm

Remove-Item -Path $targetfile -Confirm

}

"Get-Content: Permission denied"

But why?
Regards



Add Members to "Delivery Management" of the Distribution Group in Office 365.

$
0
0

Hi

we need to import File to add the list of members to the "Delivery Management" of the distribution groups. Is there any command or script is available.

Viewing all 21975 articles
Browse latest View live


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