copy-item cannot bind argument to parameter 'path' because it is null - powershell

This one has me stumped. I have already searched on "copy-item cannot bind argument to parameter 'path' because it is null", and found several posts where the answer involved fixing the syntax so that the first parameter is not null. To the best of my knowledge, my first parameter is not null, and is also of the correct type, and I am still getting the same error. I also have a very similar script running on another server without problems, and which was the template I developed this from.
The script is in a file called 'weekly-archive.ps1' and is being invoked in the PowerShell console by '.\weekly-archive.ps1'.
I am running PowerShell 2.0 on Windows Server 2008 R2
Here is the script segment in question, complete with extra stuff to print the variables before use:
$pathtosource = "\\domainname\backup\servers\windowsimagebackup\"
$pathtodest = "G:\backup\servers\"
$images = Get-ChildItem $pathtodest
foreach ($_ in $images)
{
$sourcepathname = $pathtosource + $_
$destpathname = $pathtodest + $_
$logresult += "`tSaving '" + $sourcepathname + "' to '" + $destpathname + "' at " + (Get-Date).ToShortTimeString() + ".`n"
$sourcepathname
$sourcepathname.GetType()
$pathtodest
$pathtodest.GetType()
Copy-Item $sourchpathname $pathtodest -recurse
$count += 1
}
And here is the resulting output for the first $_ in $images, showing that neither argument is null, and both arguments are actually strings:
PS D:\Administration> .\weekly-archive.ps1
\\domainname\backup\servers\windowsimagebackup\DC-1
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
G:\backup\servers\
True True String System.Object
Copy-Item : Cannot bind argument to parameter 'Path' because it is null.
At D:\Administration\weekly-archive.ps1:80 char:12
+ Copy-Item <<<< $sourchpathname $pathtodest -recurse
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
I also tried using the '-path' and '-destination' flags, which as AFAIK are optional. If I replace '$sourcepathname' in on the copy-item line in the script with a literal string, there is no error.
Finally, the following lines typed directly into the PowerShell Console work perfectly:
$sourcepathname = "\\domainname\backup\servers\windowsimagebackup\DC-1"
$pathtodest = "G:\backup\servers\"
copy-item $sourcepathname $pathtodest -recurse
So, something is clearly wrong with my use of '$sourcepathname', but I can't find it. Please do not hesitate to demonstrate my ignorance....

There is a typo on the copy-item line of the script. You have $sourchpathname and it should be $sourcepathname.

Related

Using CVS file to map network drives - PowerShell

I am developing a couple of PowerShell scripts to help speed up the process of migrating user data from an old workstation to a new one. Currently trying to make one to help with retrieving and then deploying mapped network drives and have hit a snagged with the deployment aspect. I am new to PowerShell and learning as I go along using the ISE to help spot some of the problem areas the script has. Here is a copy of what the script currently looks like and the error I am receiving when trying to run it on the machine.
# Import drive list.
$mappedDrives = Import-Csv C:\Users\########\Desktop\WIP_Scripts\MasterCopy\mappedDrives.csv
$mappedDrives | %{$_ -replace ":"}
foreach ($Name in $mappedDrives) {
New-PSDrive -Name $Name.Name -PSProvider FileSystem -Root "ProviderName" -Persist -ErrorAction Continue
}
Once I have it working Ill make the edits for where the import comes from. The errors I am currently receiving are:
New-PSDrive : Cannot process the drive name because the drive name contains one or more of
the following characters that are not valid: ; ~ / \ . :
At C:\Users\#######\Desktop\WIP_Scripts\MasterCopy\ImportMappedDrives.ps1:8 char:5
+ New-PSDrive -Name $Name.Name -PSProvider FileSystem -Root "Provid ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-PSDrive], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.NewPSDriveCommand
New-PSDrive : Cannot process the drive name because the drive name contains one or more of
the following characters that are not valid: ; ~ / \ . :
At C:\Users\#######\Desktop\WIP_Scripts\MasterCopy\ImportMappedDrives.ps1:8 char:5
+ New-PSDrive -Name $Name.Name -PSProvider FileSystem -Root "Provid ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-PSDrive], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.NewPSDriveCommand
New-PSDrive : Cannot process the drive name because the drive name contains one or more of
the following characters that are not valid: ; ~ / \ . :
At C:\Users\#######\Desktop\WIP_Scripts\MasterCopy\ImportMappedDrives.ps1:8 char:5
+ New-PSDrive -Name $Name.Name -PSProvider FileSystem -Root "Provid ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-PSDrive], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.NewPSDriveCommand
For the script used to retrieve the drive information:
$mappedDrives = #()
$Name = Get-WmiObject -ClassName Win32_MappedLogicalDisk | Select Name, ProviderName
foreach ($Name in $Name) {
if ($Name. ProviderName) {
$mappedDrives += Select-Object Name, ProviderName -InputObject $Name
}
}
$mappedDrives | Export-Csv mappedDrives.csv
MappedDrives.csv Output
Also attached is what the mappeddrives.csv output looks like for the retrieval. I thought that the csv file may be causing the invalid character arguements since the Name found within the csv file includes the ":" character. Also I am a bit confused on whether or not it will be able to see the "ProviderName" within the csv file or if I need to declare it in order for the script to add it to its argument. Again I am extremely new to Powershell so lots of what I have written down is what I have found from this site, Microsoft, or other blogs/forums and trying to Frankenstein together a working script. Any feedback on how to improve or get this to work and/or why using another method would be better in this situation would be greatly appreciated.
###Revision 1###
Utilizing the new script provided by RetiredGeek
# Import drive list.
$CFSArgs = #{PropertyNames = "Name", "ProviderName"
Delimiter = ','}
$MappedDrives = (Get-Content "G:\BEKDocs\Scripts\Test\mappedDrives.csv") |
ConvertFrom-String #CFSArgs
for ($cnt = 1; $cnt -lt $MappedDrives.count; $cnt++) {
$NPSDArgs =
#{Name = $(($MappedDrives[$cnt].Name).Substring(0,1))
PSProvider = "FileSystem"
Root = "$($MappedDrives[$cnt].ProviderName)"
Persist = $True
ErrorAction = "Continue"
}
New-PSDrive #NPSDArgs
}
I am now receiving the following error:
New-PSDrive : When you use the Persist parameter, the root must be a file system location
on a remote computer.
At C:\Users\######\Desktop\MasterCopy\Test2.ps1:16 char:9
+ New-PSDrive #NPSDArgs
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (":PSDriveInfo) [New-PSDrive], NotSupported
Exception
+ FullyQualifiedErrorId : DriveRootNotNetworkPath,Microsoft.PowerShell.Commands.NewPSD
riveCommand
The two questions I have now are:
Would it be more appropriate to use "Net use" instead of "New-PSDrive" for what I am trying to achieve(which is mapping a network drive to a computer using the cvs file created)?
If the use of the New-PSDrive cmdlet is a non-issue how do I rectify the error the script is currently outputting?
Thanks again to RetiredGeek and Theo for your inputs.
FT,
You need to evaluate your arguments in the New-PSDrive line.
Using Substring there eliminates code and makes it more efficient.
I had problems using Import-CSV so I switched to Get-Content and adjusted
# Import drive list.
$CFSArgs = #{PropertyNames = "Name", "ProviderName"
Delimiter = ','}
$MappedDrives = (Get-Content "G:\BEKDocs\Scripts\Test\mappedDrives.csv") |
ConvertFrom-String #CFSArgs
for ($cnt = 1; $cnt -lt $MappedDrives.count; $cnt++) {
$NPSDArgs =
#{Name = $(($MappedDrives[$cnt].Name).Substring(0,1))
PSProvider = "FileSystem"
Root = "$($MappedDrives[$cnt].ProviderName)"
Scope = "Global"
Persist = $True
ErrorAction = "Continue"
}
New-PSDrive #NPSDArgs -WhatIf
}
I used the -WhatIf parameter since I don't have your targets available but it showes what would have been done.
Output:
What if: Performing the operation "New drive" on target "Name: X Provider: Micro
soft.PowerShell.Core\FileSystem Root: \\hapi\desktop$\Decommission Log".
What if: Performing the operation "New drive" on target "Name: Y Provider: Micro
soft.PowerShell.Core\FileSystem Root: \\gonzo\Temp\AZ".
What if: Performing the operation "New drive" on target "Name: Z Provider: Micro
soft.PowerShell.Core\FileSystem Root: \\gonzo\Temp\001".
PS>
Update 1:
Further testing on my network (Peer-to-Peer) reveals that adding the Scope parameter (see above) will create the mapping, even though you get the same message, and it will last until you Reboot! It does NOT however persist after the reboot so it is not doing what it should. I still don't understand why it the message is displayed as the root is on another computer. Also, the mapping doesn't show in File Explorer although I can open a command prompt and successfully do a DIR on the drive.
Update 2:
I tried another test mapping to my Synology NAS and it worked w/o the error message. But, alas it did NOT persist a reboot!

using powershell invoke-expression to run code output

I have been doing a lot of reading on invoke-expression (also known as iex) and I'm having trouble getting it to work for me.
My understanding is, it will run any powershell code you give to it. However, when I run my tests on it, it does not run the code.
Example:
## testcode.ps1
$myvar = "i am here"
if ($myvar -ne $null) {
"($myvar) variable is Full"
} else {
"($myvar) variable is Empty"
}
Now, if I cat(gc) this file and I pass it to iex, it outputs a bunch of errors. Same thing happens when I save the code into a variable and then feed the variable to iex. Neither works.
Despite the fact that I've tried numerous examples, I feel there's something minor I'm doing wrong that I'm hoping someone can point out for me.
I'm new to Windows scripting, so please bear with me. These are the results of the tests I performed:
First Test:
PS C:\Users\J> gc C:\Users\J\testcode.ps1 | iex
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At line:1 char:31
+ cat C:\Users\J\testcode.ps1 | iex
+ ~~~
+ CategoryInfo : InvalidData: (:PSObject) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
iex : At line:1 char:23
+ if ($myvar -ne $null) {
+ ~
Missing closing '}' in statement block or type definition.
At line:1 char:31
+ cat C:\Users\J\testcode.ps1 | iex
+ ~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : MissingEndCurlyBrace,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Second Test:
PS C:\Users\J> $scriptBlock = gc C:\Users\J\testcode.ps1
PS C:\Users\J>
PS C:\Users\J> iex -Command "$scriptBlock"
iex : At line:1 char:23
+ $myvar = "i am here" if ($myvar -ne $null) { "($myvar) variable ...
+ ~~
Unexpected token 'if' in expression or statement.
At line:1 char:1
+ iex -Command "$scriptBlock"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.InvokeExpressionCommand
PS C:\Users\J>
I'm aware that I can just run the file containing the code. However, I need help figuring out how iex works and what it is I'm doing wrong.
Please kindly advise.
First things first:
Invoke-Expression should generally be avoided and used only as a last resort, due to its security risks. In short: avoid it, if possible, given that superior alternatives are usually available. If there truly is no alternative, only ever use it on input you either provided yourself or fully trust - see this answer.
For the record: in the case at hand, the superior alternative is to directly invoke the script file:
# Prepend `& `, if the script file path is quoted or references a variable.
C:\Users\J\testcode.ps1
Invoke-Expression (iex) accepts multiple strings via the pipeline, and evaluates each individually, as a self-contained script.
Therefore, you must provide the contents of your script as a whole, as a single string, which is what Get-Content's (gc's) -Raw switch does[1]:
Get-Content -Raw C:\Users\J\testcode.ps1 | Invoke-Expression
Alternatively, pass the script-file contents as an argument:
Invoke-Expression (Get-Content -Raw C:\Users\J\testcode.ps1)
Note that passing the string to evaluate as an argument truly only accepts a single string, so the command would fail without -Raw.
[1] By default, the Get-Content cmdlet reads a file line by line, passing each line through the pipeline as it is being read.
$myvar = "I'm Here"
#Using Invoke-Expression - Accepts a STRING as Input
$SBCode = 'if ($Null -ne $myvar) {"($myvar) variable is Full"}' +
'else {"`$myvar variable is Empty"}'
Clear-Host
"Before Invoke-Expression `$myvar = $myvar"
$Result = Invoke-Expression $SBCode
"Invoke-Expression Returns: $Result"
#Using Invoke-Command - Accepts Script Block as Input
$SBCode = {
if ($myvar -ne $null) {
"($myvar) variable is Full"
}
else {
"`$myvar variable is Empty"
}
} #End $SBCode Script Block
"Before Invoke-Command `$myvar = $myvar"
$Result = Invoke-Command -ScriptBlock $SBCode
"Invoke-Command Returns: $Result"
Results:
Before Invoke-Expression $myvar = I'm Here
Invoke-Expression Returns: (I'm Here) variable is Full
Before Invoke-Command $myvar = I'm Here
Invoke-Command Returns: (I'm Here) variable is Full
# After changing $MyVar = $Null
Before Invoke-Expression $myvar =
Invoke-Expression Returns: $myvar variable is Empty
Before Invoke-Command $myvar =
Invoke-Command Returns: $myvar variable is Empty
HTH
You can use out-string to convert output into string.
cat C:\Users\J\testcode.ps1 | out-string | Invoke-Expression

PowerShell - Add-Content- Unable to add multiple vars to a file

I'm trying to add an expression to a log file which contains Date,Time some data separated by ";". Unfortunately I get an error every time I change the position of the items in the -value brackets.
Whats seems to be wrong?
This is the code :
Add-Content -path C:\...\outlog.txt -Value($Date + ';' + $Time + ';Checked;' + $strFileName)
This is the error :
Cannot convert argument "1", with value: ";", for "op_Addition" to type "System.TimeSpan": "Cannot convert
value ";" to type "System.TimeSpan". Error: "String was not recognized as a valid TimeSpan.""
At C:\...\Untitled1.ps1:8 char:64
+ ... \outlog.txt -Value($($Date + ';' + $Time + ';'+ $str))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Try this -
Add-Content -path C:\...\outlog.txt -Value("$Date; $Time; Checked; $strFileName")
If you look at get-help Add-Content -full, and look at the -value parameter, you will see -
-Value <Object[]>
Specifies the content to be added. Type a quoted string, such as "This data is for internal use only", or
specify an object that contains content, such as the DateTime object that Get-Date generates.
You cannot specify the contents of a file by typing its path, because the path is just a string, but you can
use a Get-Content command to get the content and pass it to the Value parameter.
Required? true
Position? 1
Default value None
Accept pipeline input? True (ByPropertyName, ByValue)
Accept wildcard characters? false
It says that it expects a quoted string or an object that contains content. It was missing in your case and hence the + operator was trying to add $date and time.

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

I need to amend DNS records on a 2008 Domain using powershell

where BRIVWTDC2 is my DC
$rec = [WmiClass]"\\BRIVWTDC2\root\MicrosoftDNS:MicrosoftDNS_ResourceRecord"
$rec | get-member -membertype method
Gives me:
TypeName: System.Management.ManagementClass#ROOT\MicrosoftDNS\MicrosoftDNS_ResourceRecord
Name MemberType Definition
---- ---------- ----------
CreateInstanceFromTextRepresentation Method System.Management.ManagementBaseObject CreateInstanceFromTextRepresentation(System.String DnsServe...
GetObjectByTextRepresentation Method System.Management.ManagementBaseObject GetObjectByTextRepresentation(System.String DnsServerName, ...
and
$rec.CreateInstanceFromTextRepresentation
Gives me:
PS C:\Windows\system32> $rec.CreateInstanceFromTextRepresentation
MemberType : Method
OverloadDefinitions : {System.Management.ManagementBaseObject CreateInstanceFromTextRepresentation(System.String DnsServerName, System.String Contain
erName, System.String TextRepresentation)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Management.ManagementBaseObject CreateInstanceFromTextRepresentation(System.String DnsServerName, System.String Containe
rName, System.String TextRepresentation)
Name : CreateInstanceFromTextRepresentation
IsInstance : True
So why can't I do
$rec.CreateInstanceFromTextRepresentation("BRIVWTDC2", "stage.testdmc.com", "SECARC in CNAME BRIVWTARC2.stage.testdmc.com")
where arg is is DC, arg 2 is zone and arg 3 is textual representation = make me an alias called SECARC for RIVWTARC2.stage.testdmc.com
I just get:
Exception calling "CreateInstanceFromTextRepresentation" : "Generic failure "
At line:1 char:42
+ $rec.CreateInstanceFromTextRepresentation <<<< ("BRIVWTDC2", "stage.testdmc.com", "'SECARC' in CNAME 'BRIVWTARC2.stage.testdmc.com'")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
Which says I am doing something fundamentally stupid....
help
SECARC needs to be the FQDN SECARC.stage.testdmc.com
It looks like you're missing a fourth out parameter on CreateInstanceFromTextRepresentation.. Try:
$rr = $null
$rec.CreateInstanceFromTextRepresentation("BRIVWTDC2",
"stage.testdmc.com",
"SECARC in CNAME BRIVWTARC2.stage.testdmc.com",
[ref] $rr )
You may have to instantiate $rr as an instance of MicrosoftDNS_ResourceRecord. I don't know how to do that.
It is permissions, we need to be someone who can change DNS ( Heads and Brick Walls :-( )
the following example creates a DNS Alias, must be run as Admin or a a user who can change DNS
# DnsChanger.ps1
# Change the DNS Entries for Arbitrary Servers
# version 0.1 15/08/2012
# Paddy Carroll
# 2 arguments (1) physical server name (2) server alias
#
# setup event source
if (! [System.Diagnostics.EventLog]::SourceExists("DnsManager"))
{
"Administrative script to create event source has not been run: DnsManager.ps1"
# which is just [System.Diagnostics.EventLog]::CreateEventSource("DnsManager", "Application")
throw 'error'
}
# initialise event
$evt=new-object System.Diagnostics.EventLog("Application")
$evt.Source="DnsManager"
$errevent=[System.Diagnostics.EventLogEntryType]::error
$infoevent=[System.Diagnostics.EventLogEntryType]::information
# set up variables
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
# get arguments
if($args.count -lt 2)
{
"Script requires two parameters, a physical server name and an alias. FDQN names will be truncated and the current domain will be appended"
$evt.WriteEntry("Wrong number of arguments supplied to DnsManager " ,$errevent,2)
throw 'error'
}
$phys = $args[0].split('.')[0]
$alias = $args[1].split('.')[0]
$filter = "ContainerName = " + [char]34 + $domain + [char]34
$filter
# test for existence of CNAMEType alias
try{
$rec = Get-WmiObject -Namespace 'root\MicrosoftDNS' -Class MicrosoftDNS_CNAMEType -filter $filter
if (!$rec)
{
# if it doesnt exist, get all AType aliases
$rec = Get-WmiObject -Namespace 'root\MicrosoftDNS' -Class MicrosoftDNS_AType - filter $filter
}
}catch{
$type = $_.Exception.getType().FullName
$detail = $_.Exception.ErrorDetails().toString()
$evt.WriteEntry("Problem getting DNS Namespace for " + $domain ,$errevent,3)
throw 'error'
}
# create the alias
try{
$rec[0].CreateInstanceFromTextRepresentation($domain,$domain,$alias + '.' + $domain + ' IN CNAME ' + $phys + '.'+$domain)
}catch{
$type = $_.Exception.getType().FullName
$detail = $_.Exception.ErrorDetails().toString()
$evt.WriteEntry("Problem creating Alias for " + $phys + " as " + $alias + " : " + $type + " : " + $detail,$errevent,1)
throw 'error'
}
$evt.WriteEntry("Alias created for " + $phys + " as " + $alias ,$infoevent,1)